javascript - React props.children 不是数组

标签 javascript reactjs

根据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/

相关文章:

android - React native custom view meet 没有 propType 问题

reactjs - 如何修复 'Static HTML elements with event handlers require a role.'?

javascript - 如何让 Jade 的外部 JSON 从 Express 渲染?

javascript - CSS 无法识别 ID 或名称

javascript - 如何根据数据属性和数组输入名称查找元素

javascript - 无状态 react 函数显示无效的 proptype,即使它是

ios - 在React Native函数中创建Alert对话框?

javascript - 在react中刷新传单 map

javascript - 在单行中运行反向循环

javascript - 悬停时仅针对图像 CSS