最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Rendering children props in pure ReactJS (functional) component - Stack Overflow

programmeradmin3浏览0评论

React v0.14 supports pure functional ponents (i.e. same input equals same output). 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="" />

// Renders this:
<a href="">;/a>

But how do you render children of the PureComponent? In regular stateful ponents you access the children with this.props.children, but this obviously doesn't work here.

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="">Google Canada</a>

What should I do?

React v0.14 supports pure functional ponents (i.e. same input equals same output). 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? In regular stateful ponents you access the children with this.props.children, but this obviously doesn't work here.

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?

Share Improve this question asked Jan 28, 2016 at 23:18 user5670895user5670895 1,57320 silver badges29 bronze badges 1
  • 1 Should it be {props.children}? – Ruan Mendes Commented Jan 28, 2016 at 23:20
Add a ment  | 

1 Answer 1

Reset to default 13

You need to add children to the destructuring assignment of the argument "props".

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

children is just a prop passed to the ponent. 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.

发布评论

评论列表(0)

  1. 暂无评论