我试图根据其类型动态呈现组件.
例如:
var type = "Example";
var ComponentName = type + "Component";
return <ComponentName />;
// Returns <examplecomponent /> instead of <ExampleComponent />
Run Code Online (Sandbox Code Playgroud)
我尝试了这里提出的解决方案React/JSX动态组件名称
这在编译时给了我一个错误(使用browserify for gulp).它期望我使用数组语法的XML.
我可以通过为每个组件创建一个方法来解决这个问题:
newExampleComponent() {
return <ExampleComponent />;
}
newComponent(type) {
return this["new" + type + "Component"]();
}
Run Code Online (Sandbox Code Playgroud)
但这对我创建的每个组件都意味着一种新方法.必须有一个更优雅的解决方案来解决这个问题.
我对建议很开放.
我的用户配置文件中有几十个字段,我正在尝试构建一种有效的方法来在适当的输入表单组件中显示它们。
例如,配置文件可能如下所示:
profile1={
name: 'Cornelius Talmadge',
phone: '1'
}
Run Code Online (Sandbox Code Playgroud)
如果我可以像这样堆叠组件......
export const FieldCatalogue = {
name: <TextField defaultValue={this.state.userProfile.name} label={"Name"} />
}
Run Code Online (Sandbox Code Playgroud)
...然后我可以做这样的事情:
for (let field in Object.keys(profile1)) {
return FieldCatalogue[field]
}
Run Code Online (Sandbox Code Playgroud)
这将是非常酷的。
Component = React.createClass({..})如果我的输入组件都是通过正常语法(例如, )构造的,那么这个问题有一个很好的答案,但是:
A。有很多样板文件
b. 我必须向每个人传递大量道具,这不是最佳选择
对我来说,完美的情况基本上是将输入组件几乎作为字符串传递,这样它们就会落入它们渲染的任何父组件的范围(状态、道具等)中。
这可能和/或可取吗?