React - How to pass props to a component passed as prop

前端 未结 1 2034
迷失自我
迷失自我 2021-02-11 14:15

I have a React component (React v15.5.4) that you can pass other components to:

class CustomForm extends React.Component {
  ...
  render() {
    return (
               


        
相关标签:
1条回答
  • 2021-02-11 14:39

    You can achieve that by using React.cloneElement.

    Like this:

    class CustomForm extends React.Component {
      ...
      render() {
        return (
          <div>
              {React.cloneElement(this.props.component,{ customProps: this.props.object })}
          </div>
        );
      }
    }
    

    Working Code:

    class Parent extends React.Component{
      render() {
        return(
          <Child a={1} comp={<GChild/>} />
        )
      }
    }
    
    class Child extends React.Component{
      constructor(){
        super();
        this.state = {b: 1};
        this.updateB = this.updateB.bind(this);
      }
      
      updateB(){
        this.setState(prevState => ({b: prevState.b+1}))
      }
      
      render(){
        var Comp = this.props.comp;
        return (
          <div>
            {React.cloneElement(Comp, {b: this.state.b})}
            <button onClick={this.updateB}>Click to update b</button>
          </div>
        );
      }
    }
    
    const GChild = props => <div>{JSON.stringify(props)}</div>;
     
    ReactDOM.render(
      <Parent />,
      document.getElementById('container')
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    
    <div id='container' />

    0 讨论(0)
提交回复
热议问题