ReactJS - findAllInRenderedTree()
React 中有一个实用的工具,名为 findAllInRenderedTree。此工具可帮助我们在应用程序中定位特定部分(称为组件)。
将我们的 React 应用程序视为一棵大树,每个组件充当一个分支。findAllInRenderedTree 方法充当友好的探索器,遍历每个分支并确定它是否与测试匹配。
工作原理如下
输入 − 探索器接收两个项目:树(我们的 React 应用程序)和测试(帮助我们找到所需内容的规则)。
遍历 − 探索器逐一遍历树的每个组件。
测试 − 探索器对每个组件进行测试。如果组件通过测试(测试返回 true),则资源管理器会将其添加到列表中。
结果 − 最后,我们将获得通过测试的所有组件的列表。
语法
findAllInRenderedTree( tree, test )
参数
tree (React.Component) − 要遍历的树的根组件。
test (function) − 接受输入并返回布尔值的测试函数。此函数确定是否应将组件包含在结果中。
返回值
此函数返回通过测试的组件数组。
示例
示例 1
要查找待办事项列表中所有已完成的项目,请使用 findAllInRenderedTree。
创建一个包含待办事项列表的 React 应用。要将任务标记为已完成,请在其旁边添加一个复选框。我们将使用 findAllInRenderedTree 分别识别和显示所有已完成的工作。
import React, { useState } from 'react'; import './App.css'; const TodoApp = () => { const [tasks, setTasks] = useState([ { id: 1, text: 'Complete task 1', completed: false }, { id: 2, text: 'Finish task 2', completed: true }, // 如果需要,添加更多任务 ]); const findCompletedTasks = () => { // 使用 findAllInRenderedTree 查找已完成的任务 const completedTasks = findAllInRenderedTree(tasks, (task) => task.completed); console.log('Completed Tasks:', completedTasks); }; return ( <div className='App'> <h2>Todo List</h2> {tasks.map((task) => ( <div key={task.id}> <input type="checkbox" checked={task.completed} readOnly /> <span>{task.text}</span> </div> ))} <button onClick={findCompletedTasks}>Find Completed Tasks</button> </div> ); }; export default TodoApp;
输出

示例 2
在此应用中,我们必须识别并显示与调色板中的颜色相关的所有组件,因此我们将使用 findAllInRenderedTree。
使用调色板创建一个 React 应用,每个颜色都充当一个组件。要发现并显示所有颜色组件,请使用 findAllInRenderedTree。
import React from 'react'; import './App.css'; const ColorPaletteApp = () => { const colors = ['red', 'blue', 'green', 'yellow', 'purple']; const findColorComponents = () => { // 使用 findAllInRenderedTree 查找颜色组件 const colorComponents = findAllInRenderedTree(colors, (color) => color); console.log('Color Components:', colorComponents); }; return ( <div className='App'> <h2>Color Palette</h2> {colors.map((color) => ( <div key={color} style={{ backgroundColor: color, height: '50px', width: '50px' }}></div> ))} <button onClick={findColorComponents}>Find Color Components</button> </div> ); }; export default ColorPaletteApp;
输出

示例 3
在此应用中,我们将定位并评估交互式测验中的所有响应组件。因此,创建一个 React 应用,其中包含一个带有问题和多项选择答案的交互式测验。使用 findAllInRenderedTree 查找和评估所选答案,并根据正确性提供反馈。
import React, { useState } from 'react'; import './App.css'; const QuizApp = () => { const [questions, setQuestions] = useState([ { id: 1, text: 'What is the capital of France?', options: ['Berlin', 'London', 'Paris'], correctAnswer: 'Paris' }, { id: 2, text: 'Which planet is known as the Red Planet?', options: ['Earth', 'Mars', 'Venus'], correctAnswer: 'Mars' }, ]); const checkAnswers = () => { // 使用 findAllInRenderedTree 查找选定的答案 const selectedAnswers = findAllInRenderedTree(questions, (question) => question.selectedAnswer); console.log('Selected Answers:', selectedAnswers); }; const handleOptionClick = (questionId, selectedOption) => { setQuestions((prevQuestions) => prevQuestions.map((question) => question.id === questionId ? { ...question, selectedAnswer: selectedOption } : question ) ); }; return ( <div className='App'> <h2>Interactive Quiz</h2> {questions.map((question) => ( <div key={question.id}> <p>{question.text}</p> {question.options.map((option) => ( <label key={option}> <input type="radio" name={`question-${question.id}`} value={option} onChange={() => handleOptionClick(question.id, option)} /> {option} </label> ))} </div> ))} <button onClick={checkAnswers}>Check Answers</button> </div> ); }; export default QuizApp;
输出

摘要
这些示例展示了 findAllInRenderedTree 方法如何在各种情况下使用,从任务管理到浏览调色板和生成交互式测验。每个应用程序都使用该方法来定位 React 树中的某些组件并与之交互。