ReactJS 教程

ReactJS 主页 ReactJS 简介 ReactJS 路线图 ReactJS 下载安装和环境配置 ReactJS 功能 ReactJS 优势和缺点 ReactJS 架构 ReactJS 创建 React 应用程序 ReactJS JSX ReactJS 组件 ReactJS 嵌套组件 ReactJS 使用组件 ReactJS 集合组件 ReactJS 样式 ReactJS 属性 (props) ReactJS 使用属性创建组件 ReactJS props 验证 ReactJS 构造函数 ReactJS 组件生命周期 ReactJS 事件管理 ReactJS 创建事件感知组件 ReactJS Expense Manager 事件 ReactJS 状态管理 ReactJS 状态管理 API ReactJS 无状态组件 ReactJS Hooks 进行状态管理 ReactJS Hooks 的组件生命周期 ReactJS 布局组件 ReactJS 分页 ReactJS Material UI ReactJS Http 客户端编程 ReactJS 表单编程 ReactJS 受控组件 ReactJS 非受控组件 ReactJS Formik ReactJS 条件渲染 ReactJS 列表 ReactJS Key 键 ReactJS 路由 ReactJS Redux ReactJS 动画 ReactJS Bootstrap ReactJS Map ReactJS 表格 ReactJS 使用 Flux 管理状态 ReactJS 测试 ReactJS CLI 命令 ReactJS 构建和部署 ReactJS 示例

Hooks

ReactJS Hooks 简介 ReactJS 使用 useState ReactJS 使用 useEffect ReactJS 使用 useContext ReactJS 使用 useRef ReactJS 使用 useReducer ReactJS 使用 useCallback ReactJS 使用 useMemo ReactJS 自定义 Hooks

ReactJS 高级

ReactJS 可访问性 ReactJS 代码拆分 ReactJS 上下文 ReactJS 错误边界 ReactJS 转发 Refs ReactJS 片段 ReactJS 高阶组件 ReactJS 与其他库集成 ReactJS 优化性能 ReactJS Profiler API ReactJS Portals ReactJS 不使用 ES6 ECMAScript ReactJS 不使用 JSX 的 React ReactJS Reconciliation ReactJS Refs 和 DOM ReactJS 渲染道具 ReactJS 静态类型检查 ReactJS 严格模式 ReactJS Web 组件

其他概念

ReactJS 日期选择器 ReactJS Helmet ReactJS 内联样式 ReactJS PropTypes ReactJS BrowserRouter ReactJS DOM ReactJS 轮播 ReactJS 图标 ReactJS 表单组件 ReactJS 参考 API

ReactJS 有用资源

ReactJS 快速指南 ReactJS 备忘录 Axios 备忘录 ReactJS 有用资源 ReactJS 讨论


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);
    
    // 测试逻辑在这里
    expect(incrementButton.textContent).toBe('Increment');
    // 附加断言
});

输出

counter app increasing 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) => {
      
      // 简单的电子邮件验证逻辑
      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.html