简体   繁体   English

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

[英]Rendering children props in pure ReactJS (functional) component

React v0.14 supports pure functional components (ie same input equals same output). React v0.14支持纯功能组件 (即相同的输入等于相同的输出)。 Props are passed in as function arguments. 道具作为函数参数传入。

// 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>

But how do you render children of the PureComponent? 但是,如何渲染PureComponent的子代? In regular stateful components you access the children with this.props.children , but this obviously doesn't work here. 在常规有状态组件中,您可以使用this.props.children访问子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>

What should I do? 我该怎么办?

You need to add children to the destructuring assignment of the argument "props". 您需要将children项添加到参数“props”的解构赋值中。

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

children is just a prop passed to the component. children只是传递给组件的道具。 In order to use it like you are using props.url you need to add it to that list so it can be "pulled out" of the props object. 为了像使用props.url一样使用它,你需要将它添加到该列表中,以便可以“拉出”props对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM