Render a React component based on its name

前端 未结 2 1708
情歌与酒
情歌与酒 2021-02-08 09:47

Context: I am developing a widget-based webapp, (like the defunct iGoogle, where users can choose which widgets they want to display). Each widget is a React component.

相关标签:
2条回答
  • 2021-02-08 10:31

    You could use an object as a lookup for the component type and keep the details of rendering it in one place:

    var components = {
      'HiWidget': HiWidget,
      'HelloWidget': HelloWidget
    }
    
    var Component = components[dataFromObj.type]
    React.render(
      <Component name={dataFromObj.name}/>,
      document.getElementById('try3')
    )
    
    0 讨论(0)
  • 2021-02-08 10:41

    JSX is a superset of JavaScript, so you can always use native JavaScript syntax inside of JSX. For example, if classes of your components are available in global space (window), you can do the following:

    React.render(
      React.createElement(window[dataFromDb.type], {name: dataFromDb.name}),
      document.getElementById('try2')
    );
    

    JSFiddle here.

    0 讨论(0)
提交回复
热议问题