ReactJS - findRenderedDOMComponentWithTag()
在 React 中,有一个很有用的函数,名为 findRenderedDOMComponentWithTag()。该函数就像一个特殊的侦探,在我们的应用程序的虚拟世界中搜索称为标签的特定组件。
当我们使用 findRenderedDOMComponentWithTag() 时,我们告诉我们的计算机程序在应用程序的虚拟表示中找到一个特定的标签,该标签称为 DOM(文档对象模型)。
该函数检查该确切标签。最有趣的部分是它期望找到一个匹配项。如果有多个或没有,则会引发异常。
语法
findRenderedDOMComponentWithTag( tree, tagName )
参数
tree − 这充当了我们虚拟环境的地图,显示所有元素及其链接方式。
tagName − 它是我们在虚拟环境中寻找的标签的名称。
返回值
函数 findRenderedDOMComponentWithTag() 给出一个结果。当我们使用此函数时,我们告诉我们的计算机程序在我们的应用程序的 DOM 中定位特定的 HTML 标签(如 div>、<span> 等)。该方法仅期望识别出与所提供标签匹配的一个标签。如果检测到多个标签或没有标签,则会抛出异常,表明存在问题。
示例
示例 − 查找标题
假设我们有一本虚拟书,我们想找到书名,即标题 (h1) 标签。因此,为了完成此任务,我们将使用 findRenderedDOMComponentWithTag(tree, 'h1')。因此,以下是此应用程序的代码 −
// 导入所需的库 import React from 'react'; import { render } from '@testing-library/react'; import { findRenderedDOMComponentWithTag } from 'testing-library'; // App 应用组件 const App = () => { return ( <div> <h1>Title of the Book</h1> </div> ); }; // 测试用例 const { container } = render(<App1 />); const headingElement = findRenderedDOMComponentWithTag(container, 'h1'); console.log(headingElement.textContent);
输出
Title of the Book
此程序的目标是使用 findRenderedDOMComponentWithTag() 函数查找并显示该标题。当我们要求应用程序定位标题(h1 标签)时,它应该返回短语"书名"。
示例 − 定位按钮
假设此应用程序中有一堆按钮。要查找并与特定按钮交互,请使用 findRenderedDOMComponentWithTag(tree, 'button')。
// 导入必要的库 import React from 'react'; import { render } from '@testing-library/react'; import { findRenderedDOMComponentWithTag } from 'testing-library'; // App 应用组件 const App = () => { return ( <div> <button onClick={() => console.log('Button 1 is clicked')}>Button 1</button> <button onClick={() => console.log('Button 2 is clicked')}>Button 2</button> </div> ); }; // 测试用例 const { container } = render(<App />); const buttonElement = findRenderedDOMComponentWithTag(container, 'button'); buttonElement.click();
输出
Button 1 is clicked
程序中有两个按钮,一个标记为"按钮 1",另一个标记为"按钮 2"。这里的目标是使用 findRenderedDOMComponentWithTag() 函数查找并与这些按钮交互。当我们按下按钮时,它应该显示一条消息,例如"单击了按钮 1"。
示例 3
让我们创建一个包含一些图像的应用程序。要找到特定图像,我们将使用 findRenderedDOMComponentWithTag(tree, 'img')。
// 导入所需的库 import React from 'react'; import { render } from '@testing-library/react'; import { findRenderedDOMComponentWithTag } from 'testing-library'; // App 应用组件 const App = () => { return ( <div> <img src="image1.jpg" alt="This is Image 1" /> <img src="image2.jpg" alt="This is Image 2" /> </div> ); }; // 测试用例 const { container } = render(<App />); const imageElement = findRenderedDOMComponentWithTag(container, 'img'); console.log(imageElement.getAttribute('alt'));
输出
This is Image 1
此应用程序中有两张照片,每张照片都显示不同的东西。目的是使用 findRenderedDOMComponentWithTag() 函数识别和显示有关这些图像的信息。例如,当我们找到一张图片时,它应该告诉我们它是什么。如果它是第一张图片,它可以说"这是图片 1。"
摘要
findRenderedDOMComponentWithTag() 方法充当数字浏览器,帮助我们在应用程序的虚拟环境中定位特定项目。它确保我们得到我们想要的东西。因此,此功能使我们的编码体验变得轻松。请记住要小心使用它,并期望它只找到一件事。如果多或少,它会通知我们。