我怎样才能将道具/背景传递给动态儿童?

Yos*_*osi 10 javascript reactjs react-jsx

我正在使用反应,我正在尝试将道具/背景传递给我的动态儿童,由dymamic儿童我的意思是儿童使用

{this.props.children}
Run Code Online (Sandbox Code Playgroud)

我怎样才能传递给这个孩子(在我的代码中我知道它的类型)上下文/道具?

在这个jsbin中有一个例子,它不适用于动态儿童. http://jsbin.com/puhilabike/1/edit?html,js,output

cod*_*tix 12

尽管@ WiredPrairie的回答是正确的,但是React.addons.cloneWithProps从React v0.13RC开始就被弃用了.更新的方法是使用React.cloneElement.一个例子:

renderedChildren = React.Children.map(this.props.children, function (child) {
 return React.cloneElement(child, { parentValue: self.props.parentValue });
});
Run Code Online (Sandbox Code Playgroud)


Wir*_*rie 10

没有一个很好的方法可以做到这一点很清楚并且传递父项的所有属性并不是一个很好的模式,如果不仔细(并且有优秀的文档),可能会导致一些非常难以遵循的代码.如果你有一个属性的子集,它很简单:

的jsfiddle

假设您正在使用React和Addons,您可以克隆React组件的子项并在其上设置新的属性值.这里,代码只复制一个被调用parentValue到每个子节点的属性.它需要在已经创建子元素时创建每个元素的克隆.

var Hello = React.createClass({
    render: function() {
        var self = this;
        var renderedChildren = React.Children.map(this.props.children,
            function(child) {
                // create a copy that includes addtional property values
                // as needed
                return React.addons.cloneWithProps(child, 
                    { parentValue: self.props.parentValue } );                
            });
        return (<div>
            { renderedChildren }            
        </div>)
        ;
    }
});

var SimpleChild = React.createClass({
    render: function() {
        return <div>Simple { this.props.id }, from parent={ this.props.parentValue }</div>
    }
});

React.render((<Hello parentValue="fromParent">
    <SimpleChild id="1" />
    <SimpleChild id="2" />
</Hello>), document.body);
Run Code Online (Sandbox Code Playgroud)

生产:

Simple 1, from parent=fromParent
Simple 2, from parent=fromParent
Run Code Online (Sandbox Code Playgroud)