通常,一個(gè)組件的子代(this.props.children
)是一個(gè)組件的數(shù)組:
var GenericWrapper = React.createClass({
componentDidMount: function() {
console.log(Array.isArray(this.props.children)); // => true
},
render: function() {
return <div />;
}
});
React.render(
<GenericWrapper><span/><span/><span/></GenericWrapper>,
mountNode
);
然而,當(dāng)只有一個(gè)子代的時(shí)候,this.props.children
將會(huì)變成一個(gè)單獨(dú)的組件,而不是數(shù)組形式。這樣就減少了數(shù)組的占用。
var GenericWrapper = React.createClass({
componentDidMount: function() {
console.log(Array.isArray(this.props.children)); // => false
// 注意:結(jié)果將是 5,而不是 1,因?yàn)?`this.props.children` 不是數(shù)組,而是 'hello' 字符串!
console.log(this.props.children.length);
},
render: function() {
return <div />;
}
});
React.render(<GenericWrapper>hello</GenericWrapper>, mountNode);
為了讓處理 this.props.children
更簡(jiǎn)單,我們提供了 React.Children utilities。