在纯ReactJS(函数式)组件中渲染子组件属性

11

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 访问子组件,但在这里显然不起作用。

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>

我应该做什么?


1
应该是{props.children}吗? - Ruan Mendes
1个回答

13

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

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

children只是传递给组件的一个属性。为了像使用props.url一样使用它,您需要将其添加到该列表中,以便可以从props对象中“提取出”它。


您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Ruan Mendes
2
纯组件将props对象作为第一个参数,因此{url,children,...}是从props解构分配到这些变量中的。很高兴它有所帮助。 - Rob Lynch
1
@anotherRobLynch:所以你的意思是我可以直接用props代替{url, children},然后直接使用props.urlprops.children吗?我一直在想为什么需要用花括号。 - user5670895
@FighterJet 那也可以。如果你的同事不习惯阅读太多的 ES6 代码,这可能是更好的方法。我个人喜欢解构的外观,因为它使 JSX 更清晰。 - Rob Lynch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接