Dynamically rendering component from string: ReactJS

后端 未结 1 1050
孤城傲影
孤城傲影 2021-01-12 08:03

I was trying to call a component dynamically like this

var Tagname = \'Species\';
options.push();

And im getting

1条回答
  •  花落未央
    2021-01-12 08:56

    Yes you can call the component dynamically, but it should be the component itself not the string.

    Like this:

    var Tagname = Species;    //component itself, not string
    ;
    

    Because JSX will get compiles into React.createElement(Component, props, ...children) and Component will be a string if it a html tag, otherwise a react component.

    So if you pass React.createElement("Species", props, ...children), react will treat it as a html tag not a react component.

    Update:

    You can do one thing, create a map for each component, Like this:

    const Map = {
      "componenet1": Component1,
      "componenet2": Component2
    }
    

    Now you can access the component using the string key, like this:

    let name = "componenet1";
    let Tagname = Map[name];
    ;
    

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