【问题标题】:Rendering children props in pure ReactJS (functional) component在纯 ReactJS(功能)组件中渲染子道具
【发布时间】:2016-05-06 13:37:54
【问题描述】:

React v0.14 支持pure functional components(即相同的输入等于相同的输出)。道具作为函数参数传入。

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

我该怎么办?

【问题讨论】:

  • 应该是{props.children}

标签: javascript reactjs


【解决方案1】:

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

const PureComponent = ({url, children}) =&gt; (...)

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

【讨论】:

  • 通常情况下,如果您的回答以“试试这个”或“我认为”开头,它可能应该是一个评论。那里没有解构赋值
  • 纯组件将 props 对象作为第一个参数,因此 {url, children, ...} 是从 props 到这些变量的解构赋值。很高兴它有帮助。
  • @anotherRobLynch:所以你的意思是我可以用props 代替{url, children} 并直接使用props.urlprops.children?我想知道为什么它需要放在大括号中。
  • @FighterJet 那也行。如果您的同事不习惯阅读大量 ES6 代码,则可能是更好的方法。我个人喜欢这种解构的外观,因为它让 JSX 更干净。
猜你喜欢
  • 2021-12-22
  • 2018-10-26
  • 2018-07-20
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 2017-03-16
  • 2019-08-22
相关资源
最近更新 更多