我正在尝试根据组件的类型动态渲染组件。
例如:
var type = "Example";
var ComponentName = type + "Component";
return <ComponentName />;
// Returns <examplecomponent /> instead of <ExampleComponent />
我尝试了这里提出的解决方案React/JSX 动态组件名称 https://stackoverflow.com/questions/28842459/react-jsx-dynamic-component-names
这在编译时给了我一个错误(使用 browserify 进行 gulp)。它需要 XML,而我使用的是数组语法。
我可以通过为每个组件创建一个方法来解决这个问题:
newExampleComponent() {
return <ExampleComponent />;
}
newComponent(type) {
return this["new" + type + "Component"]();
}
但这意味着我创建的每个组件都有一个新方法。必须有一个更优雅的解决方案来解决这个问题。
我非常愿意接受建议。
EDIT:正如所指出的GMF佩雷拉 https://stackoverflow.com/users/622383/gmfvpereira这些天有一个官方文档条目:https://reactjs.org/docs/jsx-in-depth.html#choosing-the-type-at-runtime https://reactjs.org/docs/jsx-in-depth.html#choosing-the-type-at-runtime
<MyComponent />
编译为React.createElement(MyComponent, {})
,它需要一个字符串(HTML 标签)或一个函数(ReactClass)作为第一个参数。
您可以将组件类存储在名称以大写字母开头的变量中。看HTML 标签与 React 组件 https://facebook.github.io/react/docs/jsx-in-depth.html#html-tags-vs.-react-components.
var MyComponent = Components[type + "Component"];
return <MyComponent />;
编译为
var MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)