简体   繁体   中英

Rendering children props in pure ReactJS (functional) component

React v0.14 supports pure functional components (ie 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 components 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?

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 component. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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