动态添加反应中的组件

Sel*_*ina 3 components reactjs

我需要通过在react中呈现它来添加组件:

<componentName ..... />
Run Code Online (Sandbox Code Playgroud)

但是,组件的名称未知且来自变量.我怎么能这样做?

Anu*_*nuj 6

您需要存储对动态组件的引用:

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'));
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅react文档.