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 },
      // Add more tasks if needed
   ]);   
   const findCompletedTasks = () => {
      // Using findAllInRenderedTree to find completed tasks
      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;

輸出

todolist complete task

示例 2

在這個應用中,我們必須識別並顯示調色盤中與顏色相關的所有元件,因此我們將使用 findAllInRenderedTree。

使用調色盤建立一個 React 應用,其中每種顏色都作為一個元件。要查詢並顯示所有顏色元件,請使用 findAllInRenderedTree。

import React from 'react';
import './App.css';

const ColorPaletteApp = () => {
const colors = ['red', 'blue', 'green', 'yellow', 'purple'];
const findColorComponents = () => {
   
   // Using findAllInRenderedTree to find color components
   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;

輸出

color palette

示例 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 = () => {
      // Using findAllInRenderedTree to find selected answers
      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;

輸出

interactive quiz

總結

這些示例顯示瞭如何在各種情況下使用 findAllInRenderedTree 方法,從任務管理到瀏覽調色盤和生成互動式測驗。每個應用都使用此方法來查詢和互動 React 樹中的特定元件。

reactjs_reference_api.htm
廣告
© . All rights reserved.