React: adding props to an existing component

后端 未结 3 1273
孤独总比滥情好
孤独总比滥情好 2021-01-31 13:57

I\'m trying to figure out how to clone an existing element with additional props.

For reference:

this.mainContent = 

        
相关标签:
3条回答
  • 2021-01-31 14:14

    If you don't want to use React.cloneElement(), you can use the following snippet:

    function AddExtraProps(Component, extraProps) {
        return <Component.type {...Component.props} {...extraProps} />;
    }
    
    0 讨论(0)
  • 2021-01-31 14:28

    React.createElement() takes either a string or a React class type as its first parameter, so that won't work if you're trying to clone an element.

    Of course, there's React.cloneElement() instead, which does a deep copy of another React element and can optionally provide new props.

    var foo = React.cloneElement(this.mainContent, {anotherMessage: "nice to meet ya!"});
    

    Should work.

    0 讨论(0)
  • 2021-01-31 14:37

    You need to clone the element and add the additional props using React.cloneElement e.g:

    var clonedElementWithMoreProps = React.cloneElement(
        this.mainContent, 
        { anotherMessage: "nice to meet ya!" }
    );
    // now render the new cloned element?
    
    0 讨论(0)
提交回复
热议问题