Render React Component assigned from an import to a variable.. how?

末鹿安然 提交于 2019-12-01 11:10:31

问题


So, I have a need for dynamic determination of which component to show.. so, for example. I have:

import Component1 from '..somepath/Component1'
import Component1 from '..somepath/Component2'

var P = {
   red: Component1,
   blue: Component2
}

render() {
  var newComponent = P[color];
  return (
     <newComponent /> // not working
     {newComponent} // not working
    newComoponent // not working

  )
}

this mapping could be huge, thus not doing a switch or if/else.

how do I get this to return in another component?


回答1:


As per the convention the component name must be with the first letter capitalised:

render() {
  var NewComponent = P[color];
  return (
     <NewComponent />
  );
}

References:

  • https://facebook.github.io/react/docs/jsx-in-depth.html#html-tags-vs.-react-components


来源:https://stackoverflow.com/questions/35327356/render-react-component-assigned-from-an-import-to-a-variable-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!