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

前端 未结 2 2047
挽巷
挽巷 2021-02-11 13:44

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

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


        
相关标签:
2条回答
  • 2021-02-11 14:34

    You have a couple of options to achieve what your asking.

    class SomeContainer extends React.Component {
      ...
      render() {
       let someObjectVariable = {someProperty: 'someValue'};
        return (
          <CustomForm 
           component={<SomeInnerComponent propFromParent={someObjectVariable}/>}
           object={someObjectVariable}
          />
        );
      }
    

    }

    Or you can clone the component prop and apply the new props as Mayank said. In your case

    class CustomForm extends React.Component {
      ...
      render() {
        return (
          <div>
            {React.cloneElement(this.props.component,
               {propFromParent:this.props.someObjectVariable})}
          </div>
      );
     }
    }
    
    0 讨论(0)
  • 2021-02-11 14:37

    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)
提交回复
热议问题