反应props.children不是数组

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>
        );
    }

};
Run Code Online (Sandbox Code Playgroud)

我将子传递给另一个组件的render()方法:

<Two>
    <Img src="/photos/tomato.jpg"/>
    <Img src="/photos/tomato.jpg"/>
</Two>
Run Code Online (Sandbox Code Playgroud)

为什么this.props.children不是数组?更重要的是,我怎样才能让它成为一体呢?

Seb*_*ist 24

React.Children源代码中挖掘后,找到了更好的解决方案.它似乎.toArray()已经在React 0.14中添加了一个方法,很快就会发布.

一旦它出来,我们将能够简单地做这样的事情:

let children = React.Children.toArray(this.props.children);
Run Code Online (Sandbox Code Playgroud)

  • 实际上有一个用于处理 props.children 的完整 API:https://facebook.github.io/react/docs/react-api.html#react.children。props.children 本身被认为是“不透明的”,不应对其实施做出任何假设 - 请参阅 https://github.com/facebook/react/issues/751。 (3认同)

The*_*ool 6

我找到了这个解决方案。它将呈现所有子级,一个或多个。

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>
Run Code Online (Sandbox Code Playgroud)