【问题标题】:Passing props to generic children将道具传递给普通孩子
【发布时间】:2016-08-21 14:37:36
【问题描述】:

有没有办法将 props 传递给通用子组件(不是您提前知道的组件)?

使Wrapper 能够将foo 传递给孩子的东西。

var Wrapper = React.createClass({
    render: function () {
        return <div>
            {this.props.children foo={2}} 
        </div>

    }
});

var App = React.createClass({
    render: function () {
        return (
            <Wrapper>
                {this.props.foo}
            </Wrapper>
        )
    }
});

jsfiddle

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    想象一下 Javascript 代码

    this.props.children foo=2
    

    这就是你的表达式从 JSX 转换成普通 JS 的内容。事实上,你不能直接将 props 传递给 children,因为 children 不是 React 组件。要使其工作,您需要通过子元素进行映射,并为每个可迭代项传递您的道具。

    接下来的问题是你不能简单地做

    this.props.children.map(child => (
      <Child foo={2} />
    ))
    

    因为,首先,您会收到 TypeError,因为 map 未定义,其次,您会丢失每个孩子的所有初始属性。

    您需要使用React.Children.map 静态函数以及React.cloneElement 才能使其工作:

    React.Children.map(children, child => React.cloneElement(child, {
      foo: 2
    }))
    

    这样,每个子元素都会保留从父元素传递过来的自己的道具,并且除了它们之外,还会接收您定义的新道具。小心它,因为你也可能无意中重新定义了一些 props 的值。


    您的示例代码将如下所示

    var Wrapper = React.createClass({
        render: function () {
            const {
                foo
            } = this.props;
    
            return (
                <div>
                    {React.Children.map(this.props.children, child => React.cloneElement(child, {
                        foo
                    }))}
                </div>
            );
        }
    });
    
    var App = React.createClass({
        render: function () {
            return (
                <Wrapper foo={2}>
                    <div>I should be a component</div>
                    <div>I should be a component, too</div>
                    <div>We all should be components</div>
                </Wrapper>
            );
        }
    });
    

    【讨论】:

    • 非常有意义。非常感谢!
    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 2018-04-09
    • 2016-03-19
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2019-10-16
    • 2018-08-25
    相关资源
    最近更新 更多