React v0.14 支持 pure functional components (即相同的输入等于相同的输出)。 Prop 作为函数参数传入。
// 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
访问子组件,但这显然在这里不起作用。
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
只是传递给组件的 Prop 。为了像使用 props.url
一样使用它,您需要将它添加到该列表中,以便它可以从 props 对象中“拉出”。
关于javascript - 在纯 ReactJS(功能)组件中渲染子 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35074013/