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 - 渲染道具

由于 React 组件是通过组合(一个组件包含另一个组件)而不是通过继承相互连接的,因此 React 组件中使用的逻辑不会直接共享给另一个组件。React 提供了多个选项来在组件之间共享逻辑,其中一个选项是渲染道具。渲染道具基本上是通过其道具将具有必要渲染逻辑的函数传递给具有核心功能的组件。因此,它被称为渲染道具。

让我们在本章中学习如何使用渲染道具。

如何使用渲染道具

让我们逐步了解如何使用渲染道具并在两个组件之间共享逻辑。让我们考虑从外部 URL 获取和呈现数据的场景。

  • 创建一个组件 FetcherComponent 来从外部 URL 获取数据,并创建一个 FetcherConsumerComponent 来使用数据并呈现它。

  • 创建一个组件 FetcherComponent,它具有针对给定 URL(props.url)的数据获取逻辑。

componentDidMount() {
   fetch(this.props.url)
   .then((response) => response.json())
   .then((data) => {
      this.setState({
         data: data
      });
   });
}

现在,更新 FetcherComponent,以便将核心渲染逻辑委托给 props(this.props.render)。

render() {
   return (
      <div>
         <h2>Fetch react component</h2>
         {this.state.data && this.props.render(this.state.data)}
      </div>
   )
}

此处,

  • this.props.render 是具有渲染逻辑的函数,任何其他组件都会通过其 props 将其传递到 FetcherComponent 中。

  • 创建一个组件 FetcherConsumerComponent,并通过传递获取的数据的渲染逻辑来渲染 FetcherComponent。

render() {
   return (<FetcherComponent url="users.json" render={(items) => (
      <ul>
         {items && items.length && items.map((item) =>
            <li key={item.id}>{item.name}</li>
         )}
      </ul>
   )} />)
}

这里,

  • items 是由 FetcherComponent 组件获取的数据。

  • 它们循环并发出 HTML 无序列表。

我们可以按照本节中定义的步骤,并在下一节中创建一个工作示例。

应用渲染道具

首先,创建一个新的 React 应用程序并使用以下命令启动它。

create-react-app myapp
cd myapp
npm start

接下来,打开 App.css (src/App.css) 并删除所有 CSS 类。然后,创建一个组件 FetchRenderProps (src/Components/FetchRenderProps.js),其数据获取逻辑如下所示 −

import React from "react";
class FetchRenderProps extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         data: []
      }
   }
   componentDidMount() {
      fetch(this.props.url)
      .then((response) => response.json())
      .then((data) => {
         console.log(data)
         this.setState({
            data: data
         });
      });
   }
   render() {
      return (
         <div>
            <h2>Fetch react component</h2>
            {this.state.data && this.props.render(this.state.data)}
         </div>
      )
   }
}
export default FetchRenderProps;

这里我们有,

  • 在 componentDidMount 事件中使用 fetch javascript 方法从外部 url 获取数据。

  • 使用通过 props 传递的 render 方法渲染获取的数据。

接下来,在 public 文件夹中创建一个文件 users.json (public/users.json) 来存储用户信息。我们将尝试使用 FetchRenderProps 组件获取它并在我们的应用程序中显示它。

[{"id":1,"name":"Fowler","age":18},
{"id":2,"name":"Donnell","age":24},
{"id":3,"name":"Pall","age":26}]

接下来,在 public 文件夹中创建一个文件 todo_list.json (public/todo_list.json),用于存储待办事项列表信息。我们将尝试使用 FetchRenderProps 组件获取它并在我们的应用程序中显示它。

[{"id":1,"title":"Learn JavaScript","is_done":true},
{"id":2,"title":"Learn React","is_done":true},
{"id":3,"title":"Learn Typescript","is_done":false

接下来,创建一个组件 SimpleRenderProps (src/Components/SimpleRenderProps.js) 来使用 FetchRenderProps 组件,如下所示 −

import React from "react";
import FetchRenderProps from "./FetchRenderProps";
class SimpleRenderProps extends React.Component {
   render() {
      return (
         <>
            <FetchRenderProps url="users.json" render={(items) => (
               <ul>
                  {items && items.length && items.map((item) =>
                     <li key={item.id}>{item.name}</li>
                  )}
               </ul>
            )} />
            <FetchRenderProps url="todo_list.json" render={(items) => (
               <ul>
                  {items && items.length && items.map((item) =>
                     <li key={item.id}>{item.title} {item.is_done && <strong>Done</strong>}</li>
                  )}
               </ul>
            )} />
         </>
      )
   }
}
export default SimpleRenderProps;

这里我们有,

  • 使用 FetchRenderProps 和 users.json 来获取和呈现用户列表

  • 使用 FetchRenderProps 和 todo_list.json 来获取和呈现待办事项列表

  • 获取用户和待办事项列表使用相同的 FetchRenderProps 组件。

接下来,打开 App.js 文件并呈现 SimpleRenderProps 组件,如下所示 −

import './App.css'
import React from 'react';
import SimpleRenderProps from './Components/SimpleRenderProps'
function App() {
   return (
      <div className="container">
         <div style={{ padding: "10px" }}>
            <div>
               <SimpleRenderProps />
            </div>
         </div>
      </div>
   );
}
export default App;

最后,在浏览器中打开应用程序并检查最终结果。应用程序将呈现如下图所示 −

应用渲染属性

摘要

渲染属性是一种在组件之间共享逻辑的有效方法。它在许多第三方组件中被广泛使用,成功率很高,并且是经过时间考验的在 React 域中共享逻辑的方法。