React - Dynamically Import Components

前端 未结 8 1690
别那么骄傲
别那么骄傲 2020-12-05 07:14

I have a page which renders different components based on user input. At the moment, I have hard coded the imports for each component as shown below:

    imp         


        
8条回答
  •  不知归路
    2020-12-05 08:03

    you could create a component building function that utilizes React.createElement. this way you can import the function from a helper file. hard to show more code in this example without more information, but you can use state helpers from this file too if your goal is to completely remove the logic from this component.

    class Main extends Component {
    
    constructor(props) {
      super();
      this.state = { displayComponent: Component1 }
    }
    
    buildComponent = () => {
      // create element takes additional params for props and children
      return React.createElement( this.state.displayComponent )
    }
    
    render() {
        var type = 'Component1';  // just an example
        return (
          
    { this.buildComponent() }
    ) }

    }

提交回复
热议问题