在纯 ReactJS(功能)组件中渲染子道具

Rendering children props in pure ReactJS (functional) component

本文关键字:组件 ReactJS 功能 在纯      更新时间:2023-09-26

React v0.14支持纯功能组件(即相同的输入等于相同的输出)。props 作为函数参数传入。

// Using ES6 arrow functions and an implicit return:
const PureComponent = ({url}) => (
  <div>
    <a href={url}>{url}</a>
  </div>
);
// Used like this:
<PureComponent url="http://www.google.ca" />
// Renders this:
<a href="http://www.google.ca">http://www.google.ca</a>

但是如何渲染纯组件的子组件呢?在常规有状态组件中,您可以使用this.props.children访问子组件,但这显然在这里不起作用。

const PureComponent = ({url}) => (
  <div>
    <a href={url}>{children}</a> // <--- This doesn't work
  </div>
);
<PureComponent url="http://www/google.ca">Google Canada</PureComponent>
// I want to render this:
<a href="http://www.google.ca">Google Canada</a>

我该怎么办?

您需要

children添加到参数"props"的解构赋值中。

const PureComponent = ({url, children}) => (...)

children只是传递给组件的道具。 为了像使用props.url一样使用它,您需要将其添加到该列表中,以便可以将其从 props 对象中"拉出"。