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

use*_*216 7 javascript reactjs

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

// 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>
Run Code Online (Sandbox Code Playgroud)

但是,如何渲染PureComponent的子代?在常规有状态组件中,您可以访问子项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>
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

Rob*_*nch 8

您需要添加children参数"props"的解构赋值.

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

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

  • 纯组件将 props 对象作为第一个参数,因此 {url, Children, ...} 是从 props 到这些变量的解构赋值。很高兴有帮助。 (2认同)