[英]Rendering children props in pure ReactJS (functional) component
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
訪問子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
只是傳遞給組件的道具。 為了像使用props.url
一樣使用它,你需要將它添加到該列表中,以便可以“拉出”props對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.