简体   繁体   中英

How can I pass props/context to dynamic childrens in react?

I am using react, and I am trying to pass props/context to my dynamic childrens, by dymamic childrens I mean childrens are render using

{this.props.children}

How can I pass to this children (In my code I know it's type) context/props?

In this jsbin there is an example that it dosen't work on dynamic childrens. http://jsbin.com/puhilabike/1/edit?html,js,output

Though @WiredPrairie's answer is correct, the React.addons.cloneWithProps is deprecated as of React v0.13RC. The updated way to do this is to use React.cloneElement . An example:

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

There's not aa great way to do this that is clear and passing all the properties of the parent isn't a great pattern and could lead to some very difficult to follow code if not done carefully (and with excellent documentation). If you have a subset of properties though, it's straightforward:

JsFiddle

Assuming you're using React with Addons, you can clone the children of a React component and set new property values on them. Here, the code just copies a property called parentValue into each child. It needs to create a clone of each element as the child element had already been created.

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

Produces:

Simple 1, from parent=fromParent
Simple 2, from parent=fromParent

Spreading props on DOM elements

https://github.com/vasanthk/react-bits/blob/master/anti-patterns/07.spreading-props-dom.md

When we spread props we run into the risk of adding unknown HTML attributes, which is a bad practice.

const Sample = () => (<Spread flag={true} domProps={{className: "content"}}/>);
const Spread = (props) => (<div {...props.domProps}>Test</div>);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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