ReactJS - isCompositeComponentWithType() 方法



眾所周知,在 React 中,每個元件都有其自己的生命週期,這意味著它們在專案中執行時會經歷不同的階段。React 提供了內建方法來控制這些過程。

現在讓我們看看 isCompositeComponentWithType() 方法。此方法告訴我們程式的給定元素是否為 React 元件。以下是我們可以使用它的方法:

語法

isCompositeComponentWithType(
   instance,
   componentClass
)

引數

在 React 中,isCompositeComponentWithType 方法需要兩個引數:

  • instance - 此引數提供我們要測試的元件例項。

  • componentClass - 此引數表示 React 元件類。

返回值

該函式將確定例項是否為此元件類的例項。該函式產生一個布林結果:

  • 如果例項是型別與 componentClass 匹配的元件,則返回 true。

  • 如果例項不是提供的 componentClass 的元件,則返回 false。

示例

示例 - 簡單應用

讓我們建立一個簡單的 React 應用,其中包含一個元件,然後在測試中使用 isCompositeComponentWithType()。我們將有一個簡單的 React 元件 (MyComponent) 和一個測試程式碼。該測試使用 isCompositeComponentWithType() 檢查渲染的元件是否為型別為“div”的複合元件。此應用的程式碼如下所示:

MyComponent.js

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

const MyComponent = () => {
   return (
      <div>
         <h1>Hello, I'm a simple component!</h1>
      </div>
   );
};
export default MyComponent;
test('MyComponent is a composite component of type "div"', () => {
   const { container } = render(<MyComponent />);
   const isComposite = isCompositeComponentWithType(container.firstChild, 'div');
   expect(isComposite).toBe(true);
});

輸出

simple component

示例 - 測試按鈕應用

這是包含 isCompositeComponentWithType() 方法的 App.js 檔案的完整程式碼,以顯示該方法的用法。

import React from 'react';
import { isCompositeComponentWithType } from 'react-dom/test-utils';

// Define App Component
const App = () => {

   // Function to show isCompositeComponentWithType()
   function myFunction() {
      var a = isCompositeComponentWithType(el);
      console.log("Is the following element a composite component? " + a);
   }
   
   // The element for testing
   const el = <div>
      <h1>element</h1>
   </div>
   
   // Return the user interface
   return (
      <div id='el'>
         <h1>React isCompositeComponentWithType() method usage</h1>
         <button onClick={myFunction}>
         Click Me !!
         </button>
      </div>
   );
}

export default App;

輸出

test button app

此程式碼顯示了一個 App 元件,該元件具有一個 myFunction 函式來顯示 isCompositeComponentWithType() 方法。當我們點選應用中的按鈕時,它將檢查 el 元素是否為複合元件並記錄結果。

假設我們正在建立一個數字店面,並且想知道我們網站的特定部分是否屬於產品列表型別。我們可以透過呼叫 isCompositeComponentWithType() 函式來實現這一點。首先,我們匯入所需的工具,構建一個驗證函式,建立一個元素(產品列表),然後在我們的網站上顯示它並帶有一個測試按鈕。

示例 - 從 API 獲取資料

現在我們將有一個應用從 API 獲取和顯示資料。還有一個測試檔案,它使用 isCompositeComponentWithType() 測試 FetchData 元件是否渲染從 API 獲取的資料。它使用 @testing-library/react 中的 render 函式來渲染元件,並使用 waitFor 來等待非同步 fetch 呼叫完成。此應用的程式碼如下所示:

// FetchData.js
import React, { useState, useEffect } from 'react';

const FetchData = () => {
   const [data, setData] = useState([]);   
   useEffect(() => {
      const fetchData = async () => {
      try {
         const response = await fetch('https://jsonplaceholder.typicode.com/todos');
         const result = await response.json();
         setData(result);
      } catch (error) {
         console.error('Error fetching data:', error);
      }
   };   
   fetchData();
   }, []);
   
   return (
      <div>
         <h1>Fetching Data from an API</h1>
         <ul>
            {data.map(item => (
               <li key={item.id}>{item.title}</li>
            ))}
         </ul>
      </div>
   );
};

export default FetchData;

FetchData.test.js

 
import React from 'react';
import { render, waitFor } from '@testing-library/react';
import FetchData from './FetchData';

// fetch function
global.fetch = jest.fn(() =>
Promise.resolve({
   json: () => Promise.resolve([{ id: 1, title: 'Sample Todo' }]),
})
);

test('FetchData renders data from API', async () => {
   const { getByText } = render(<FetchData />);
   
   // Wait for the fetch call
   await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
   
   const todoItem = getByText('Sample Todo');
   expect(todoItem).toBeInTheDocument();
});

輸出

fetching data from api

總結

isCompositeComponentWithType() 是一個有用的工具,可以識別應用中的 React 元件型別並在測試或除錯情況下檢查其有效性。我們建立了三個不同的應用來展示此函式的用法。

reactjs_reference_api.htm
廣告

© . All rights reserved.