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

前端 未结 2 2051
挽巷
挽巷 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:37

    You can achieve that by using React.cloneElement.

    Like this:

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

    Working Code:

    class Parent extends React.Component{
      render() {
        return(
          } />
        )
      }
    }
    
    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 (
          
    {React.cloneElement(Comp, {b: this.state.b})}
    ); } } const GChild = props =>
    {JSON.stringify(props)}
    ; ReactDOM.render( , document.getElementById('container') );
    
    
    
    

提交回复
热议问题