Seb*_*ist 13 javascript reactjs
根据反应文档,如果一个组件有多个子组件,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()方法:
<Two>
    <Img src="/photos/tomato.jpg"/>
    <Img src="/photos/tomato.jpg"/>
</Two>
为什么this.props.children不是数组?更重要的是,我怎样才能让它成为一体呢?
Seb*_*ist 24
在React.Children源代码中挖掘后,找到了更好的解决方案.它似乎.toArray()已经在React 0.14中添加了一个方法,很快就会发布.
一旦它出来,我们将能够简单地做这样的事情:
let children = React.Children.toArray(this.props.children);
我找到了这个解决方案。它将呈现所有子级,一个或多个。
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>
| 归档时间: | 
 | 
| 查看次数: | 12707 次 | 
| 最近记录: |