我尝试编写一个React组件.对于html标题标签(h1,h2,h3等),其中标题优先级根据我们在props中定义的优先级动态变化.
这就是我尝试做的事情.
<h{this.props.priority}>Hello</h{this.props.priority}>
预期产量:
<h1>Hello</h1>
这不起作用.有没有可行的方法来做到这一点?
我试图根据其类型动态呈现组件.
例如:
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)
但这对我创建的每个组件都意味着一种新方法.必须有一个更优雅的解决方案来解决这个问题.
我对建议很开放.
I am using react-icons and I have a JSON file as follows:
social: {
twitter: {
icon: 'FaTwitter',
link: 'twitterlink',
},
linkedin: {
icon: 'FaLinkedIn',
link: 'linkedinlink',
},
github: {
icon: 'FaGithub',
link: 'githublink',
},
}
Run Code Online (Sandbox Code Playgroud)
I am trying to dynamically create the icons by looping through the JSON, but I'm having a lot of trouble making it work.
Here are snippets of what I've already tried so far along with the outputs and the errors produced in the console: …