Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

And I have a different component that uses it:

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

Everything renders fine, but I want to pass someObjectVariable prop to the child component inside CustomForm (in this case that'll be SomeInnerComponent), since in the actual code you can pass several components to it instead of just one like the example.

Mind you, I also need to pass SomeInnerComponent its own props.

Is there a way to do that?

question from:https://stackoverflow.com/questions/48919320/react-how-to-pass-props-to-a-component-passed-as-prop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
319 views
Welcome To Ask or Share your Answers For Others

1 Answer

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' />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...