简体   繁体   English

将道具传递给通用儿童

[英]Passing props to generic children

Is there way to pass props to a generic child (not a component that you know ahead)? 有没有办法将道具传递给一个普通孩子(不是你前面知道的组件)?

Something that would make Wrapper be able to pass foo to children. 可以使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 的jsfiddle

Imagine Javascript code 想象一下Javascript代码

this.props.children foo=2

this is what your expression is transpiled into from JSX into plain JS. 这就是你的表达式从JSX转换成普通的JS。 The fact is, you can't pass props to children directly because children isn't a React component. 事实是,你不能直接将道具传递给children ,因为children不是React组件。 To make it work, you need to map through children and pass your props per every item of iterable. 为了使其工作,您需要映射子项并根据每个可迭代项传递道具。

The problem that comes next is that you can't simply do 接下来的问题是你不能简单地做到

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

because, first, you'll receive TypeError because map is undefined, and second, you'd lose all initial props of every child. 因为,首先,你会收到TypeError,因为map是未定义的,其次,你会丢失每个孩子的所有初始道具。

You'll need to use React.Children.map static function as well as React.cloneElement to make it work: 您需要使用React.Children.map静态函数以及React.cloneElement来使其工作:

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

This way, every child element preserves its own props passed from parent element and, in addition to them, receive new props you define. 这样,每个子元素都会保留从父元素传递的自己的道具,并且除了它们之外,还会接收您定义的新道具。 Be careful with it because you may unintentionally redefine values of some props, too. 小心它,因为你也可能无意中重新定义了一些道具的值。


Your example code will then look like 您的示例代码将如下所示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM