React / JSX动态组件名称

JavaScript

米亚凯

2020-03-11

我正在尝试根据组件的类型动态呈现组件。

例如:

var type = "Example";
var ComponentName = type + "Component";
return <ComponentName />; 
// Returns <examplecomponent />  instead of <ExampleComponent />

我尝试了这里提出的解决方案React / JSX动态组件名称

那给我一个编译时的错误(使用browserify进行gulp)。我使用数组语法的地方应该是XML。

我可以通过为每个组件创建一个方法来解决此问题:

newExampleComponent() {
    return <ExampleComponent />;
}

newComponent(type) {
    return this["new" + type + "Component"]();
}

但这将意味着为我创建的每个组件提供一种新方法。必须对此问题有一个更优雅的解决方案。

我很乐意提出建议。

第660篇《React / JSX动态组件名称》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
宝儿Pro 2020.03.11

我使用了一些不同的方法,因为我们一直都知道我们的实际组件,因此我认为应该使用开关盒。在我的情况下,组件总数也不超过7-8。

getSubComponent(name) {
    let customProps = {
       "prop1" :"",
       "prop2":"",
       "prop3":"",
       "prop4":""
    }

    switch (name) {
      case "Component1": return <Component1 {...this.props} {...customProps} />
      case "Component2": return <Component2 {...this.props} {...customProps} />
      case "component3": return <component3 {...this.props} {...customProps} />

    }
  }
Sam神乐番长 2020.03.11

如果您的组件是全局组件,则可以执行以下操作:

var nameOfComponent = "SomeComponent";
React.createElement(window[nameOfComponent], {});

阳光凯 2020.03.11

<MyComponent />编译为React.createElement(MyComponent, {}),它期望将字符串(HTML标记)或函数(ReactClass)作为第一个参数。

您可以只将组件类存储在名称以大写字母开头的变量中。参见HTML标签与React组件

var MyComponent = Components[type + "Component"];
return <MyComponent />;

编译为

var MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android