javascript React props.children 不是数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32672966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React props.children is not array
提问by Sebastian Sandqvist
According to the react docs, if a component has multiple children, this.props.children should be an array.
根据react docs,如果一个组件有多个子组件,则 this.props.children 应该是一个数组。
I have the following component:
我有以下组件:
export class Two extends React.Component {
componentDidMount() {
console.log(Array.isArray(this.props.children)); // false
}
render() {
return(
<div>
{this.props.children}
</div>
);
}
};
Which I pass children to in another component's render() method:
我在另一个组件的 render() 方法中将子项传递给它:
<Two>
<Img src="/photos/tomato.jpg"/>
<Img src="/photos/tomato.jpg"/>
</Two>
Why is this.props.children not an array? More importantly, how can I get it to be one?
为什么 this.props.children 不是数组?更重要的是,我怎样才能让它成为一个?
回答by Sebastian Sandqvist
Found a better solution to this after some digging in the React.Children source. It looks like a .toArray()
method has been added in React 0.14, soon to be released.
在对React.Children 源代码进行一些挖掘后找到了一个更好的解决方案。看起来.toArray()
在 React 0.14 中添加了一个方法,即将发布。
Once it is out we will be able to simply do something like this:
一旦它出来,我们将能够简单地做这样的事情:
let children = React.Children.toArray(this.props.children);
回答by Amsvartner
You might find the spread syntax useful in this case. Have you tried it out?
在这种情况下,您可能会发现传播语法很有用。你试过了吗?
<div>
{ [...this.props.children] }
</div>
Combine with map to manipulate the output.
结合 map 来操作输出。
<div>
{ [...this.props.children].map(obj => <div style="someStyling"> {obj} </div> ) }
</div>
回答by The Fool
I found this solution. It will render all children, one or more.
我找到了这个解决方案。它将渲染所有孩子,一个或多个。
const BigMama = ({ children, styles, className }) => {
return (
<div
styles={{styles}}
className={(className ? className : '')}
>
{
React.Children.map(children, (child) =>
<React.Fragment>{child}</React.Fragment>)
}
</div>)
}
<BigMama
styles={{border: 'solid groove'}}
className='bass-player'
>
<h1>Foo</h1>
<h2>Bar</h2>
<h3>Baz</h3>
<h4>Impossibru!</h4>
<BigMama>
回答by Milind Agrawal
There are many ways and some are mentioned above already but if you wanna keep it simple and want to achieve this without any utility then below should work
有很多方法,上面已经提到了一些方法,但是如果您想保持简单并想在没有任何实用程序的情况下实现这一点,那么下面应该可以
const content = [
<Img src="/photos/tomato.jpg"/>,
<Img src="/photos/tomato.jpg"/>
];
<Two>
{content}
</Two>