ReactJS - findRenderedComponentWithType()



React.js 中有一個名為 findRenderedComponentWithType() 的函式。此函式類似於另一個名為 scryRenderedComponentsWithType() 的函式,但其工作方式不同。findRenderedComponentWithType() 背後的基本思想是在渲染樹中定位並返回給定的元件。

findRenderedComponentWithType() 的目標是在渲染樹(React 元件的結構)中搜索給定的元件。與其他幾個函式相比,findRenderedComponentWithType() 只需要一個匹配項。如果有多個匹配項或根本沒有匹配項,則會丟擲異常。

語法

findRenderedComponentWithType(tree, componentClass)

引數

tree − 這是我們要搜尋的 React 元件的渲染樹。

componentClass − 這是我們想要的元件型別,由其類給出。

返回值

findRenderedComponentWithType() 返回渲染樹中與給定類型別匹配的單個 React 元件。如果只有一個匹配項,它將返回該元件。如果沒有匹配項或多個匹配項,它將丟擲異常,指示預期匹配數存在問題。

示例

示例 - 計數器應用和測試

這是一個基本的計數器應用,其中我們將有一個按鈕用於遞增計數器。然後,我們將為此元件建立測試以測試其功能。讓我們看看應用和測試的程式碼:

CounterApp.js

import React, { useState } from 'react';

const CounterApp = () => {
   const [count, setCount] = useState(0);   
   const increment = () => {
      setCount(count + 1);
   };
   
   return (
      <div>
         <h1>Counter App</h1>
         <p>Count: {count}</p>
         <button onClick={increment}>Increment</button>
      </div>
   );
};

export default CounterApp;

CounterApp.test.js

import React from 'react';
import { render } from '@testing-library/react';
import { findRenderedComponentWithType } from 'react-dom/test-utils';
import CounterApp from './CounterApp';

test('finds and interacts with the "Increment" button', () => {
   const { container } = render(<CounterApp />);
   const incrementButton = findRenderedComponentWithType(container, HTMLButtonElement);
   
   // The testing logic goes here
   expect(incrementButton.textContent).toBe('Increment');
   // Additional assertions
});

輸出

counter app increment 1

示例 - 電子郵件驗證應用和測試

現在,我們將建立一個小型應用程式,該應用程式將驗證使用者的電子郵件地址,並使用 findRenderedComponentWithType() 方法建立測試程式碼:

FormValidationApp.js

import React, { useState } from 'react';

const FormValidationApp = () => {
   const [email, setEmail] = useState('');
   const [validEmail, setValidEmail] = useState(false);   
   const handleEmailChange = (e) => {
      const newEmail = e.target.value;
      setEmail(newEmail);
      setValidEmail(validateEmail(newEmail));
   };
   
   const validateEmail = (input) => {
      
      // Simple email validation logic
      return /\S+@\S+\.\S+/.test(input);
   };
   
   return (
      <div>
         <h1>Form Validation App</h1>
         <label>Email:</label>
         <input type="text" value={email} onChange={handleEmailChange} />
         {validEmail ? <p>Email is valid!</p> : <p>Email is not valid.</p>}
      </div>
   );
};

export default FormValidationApp;

FormValidationApp.test.js

import React from 'react';
import { render } from '@testing-library/react';
import { findRenderedComponentWithType } from 'react-dom/test-utils';
import FormValidationApp from './FormValidationApp';

test('finds and validates the email input', () => {
   const { container } = render(<FormValidationApp />);
   const emailInput = findRenderedComponentWithType(container, HTMLInputElement);
   
   //testing logic
   expect(emailInput.type).toBe('text');
});

輸出

form validation app email

示例 - 切換開關應用和測試

在這個應用中,我們將使用切換功能,其中具有開啟和關閉功能,然後我們將使用 findRenderedComponentWithType() 為此功能建立測試。此應用和測試程式碼如下:

ToggleSwitchApp.js

import React, { useState } from 'react';

const ToggleSwitchApp = () => {
   const [isOn, setIsOn] = useState(false);
   
   const toggleSwitch = () => {
      setIsOn(!isOn);
   };
   
   return (
      <div>
         <h1>Toggle Switch App</h1>
         <label>
            <input type="checkbox" checked={isOn} onChange={toggleSwitch} />
            {isOn ? 'ON' : 'OFF'}
         </label>
      </div>
   );
};

export default ToggleSwitchApp;

ToggleSwitchApp.test.js

import React from 'react';
import { render } from '@testing-library/react';
import { findRenderedComponentWithType } from 'react-dom/test-utils';
import ToggleSwitchApp from './ToggleSwitchApp';

test('finds and interacts with the toggle switch', () => {
   const { container } = render(<ToggleSwitchApp />);
   const toggleSwitch = findRenderedComponentWithType(container, HTMLInputElement);
   
   // testing logic 
   expect(toggleSwitch.type).toBe('checkbox');
});

輸出

switch on switch off

總結

在本教程中,我們學習了 findRenderedComponentWithType(),這是一個 React.js 函式,有助於在渲染樹中定位特定元件。我們分析了它的引數,然後利用這些知識建立了三個不同的 React.js 應用。我們不僅理解了這個概念,而且還將其付諸實踐,使我們的學習更加實踐化。

reactjs_reference_api.htm
廣告
© . All rights reserved.