根据react docs ,如果一个组件有多个 child ,this.props.children 应该是一个数组。
我有以下组件:
export class Two extends React.Component {
componentDidMount() {
console.log(Array.isArray(this.props.children)); // false
}
render() {
return(
<div>
{this.props.children}
</div>
);
}
};
我在另一个组件的 render() 方法中将 child 传递给它:
<Two>
<Img src="/photos/tomato.jpg"/>
<Img src="/photos/tomato.jpg"/>
</Two>
为什么 this.props.children 不是数组?更重要的是,我怎样才能让它成为一个?
最佳答案
在 React.Children source 中进行一些挖掘后找到了更好的解决方案.看起来 React 0.14 中添加了一个 .toArray()
方法,即将发布。
一旦它出来,我们就可以简单地做这样的事情:
let children = React.Children.toArray(this.props.children);
它记录在 https://reactjs.org/docs/react-api.html#reactchildren 中
关于javascript - React props.children 不是数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32672966/