繁体   English   中英

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

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

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>

但是,如何渲染PureComponent的子代? 在常规有状态组件中,您可以使用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>

我该怎么办?

您需要将children项添加到参数“props”的解构赋值中。

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

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

暂无
暂无

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

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