2017-07-10 76 views
1

我需要通過使其添加組分反應:在動態添加組分反應

<componentName ..... /> 

然而,組件的名稱是未知的,從一個可變的到來。 我該如何渲染?

+0

參考此答案https://stackoverflow.com/questions/36941829/how-to-load-component-dynamically-in-reactjs/46188808#46188808 –

回答

1

您可以創建一個導出所有不同組件

// Components.js 
export Foo from './Foo' 
export Bar from './Bar' 

然後將它們導入文件中的所有

import * as Components from './Components' 

那麼你可以動態地創建他們基於變量/道具:

render() { 
    // this.props.type = 'Foo' 
    // renders a Foo component 
    const Component = Components[this.props.type]; 
    return Component && <Component />; 
} 
3

您需要引用存儲到動態組件:

import ComponentName from 'component-name' 

class App extends Component { 
    constructor(props) { 
     super(props) 

     this.components = { 
      'dynamic-component': ComponentName 
     } 
    } 

    render() { 
     // notice capitalization of the variable - this is important! 
     const Name = this.components[this.props.componentName]; 

     return (
     <div> 
      <Name /> 
     </div> 
    ) 
    } 
}; 

render(<App componentName={ 'dynamic-component' } />, document.getElementById('root')); 

更多信息,請參見react docs

0
Okay, for me this worked: 

import {Hello} from 'ui-hello-world'; 

let components = {}; 

components['Hello'] = Hello; 
export default components; 

然後在我的課上: 從'..... json'導入customComps; .... let Component = Custom.default [customComps.componentName];

 return (
     <Component