Javascript 从条件语句呈现多个React组件
我有一个Javascript 从条件语句呈现多个React组件,javascript,reactjs,Javascript,Reactjs,我有一个定义对象,根据每个表单的“类型”,我呈现一个特定的组件。例如: const definition = { name: "test", id: 1, form: [ {type: "text"}, {type: "checkbox"}, {type: "radio"}] }; 因此,要访问表单类型,我只需做一个简单的映射: const definitionTypes = definitions.form.map ( form => form.type ) 现在
定义
对象,根据每个表单的“类型”,我呈现一个特定的组件。例如:
const definition =
{
name: "test",
id: 1,
form: [
{type: "text"},
{type: "checkbox"},
{type: "radio"}]
};
因此,要访问表单类型,我只需做一个简单的映射:
const definitionTypes = definitions.form.map ( form => form.type )
现在,我有一个存储在definitionTypes
上的所有表单类型条目的数组,我有三个组件需要根据definitionTypes数组中的关键字进行渲染。所以对于“文本”,我有一个我正在导入的组件,叫做
,等等
我遇到的问题是找到一个解决方案,根据definitionTypes数组中的类型返回多个组件。最终目标是从该阵列渲染这3个组件:
// if definitionTypes includes "text" then render...
<DefinitionText />
// also if definitionTypes includes "checkbox" then render...
<DefinitionCheckbox />
// also if definitionTypes includes "radio" then render...
<DefinitionRadio />
//如果定义类型包括“文本”,则呈现。。。
//此外,如果定义类型包括“复选框”,则呈现。。。
//此外,如果定义类型包括“收音机”,则渲染。。。
我尝试使用
if/else
语句将每个组件推送到results
变量,然后呈现该变量,但results
变量会发回一个错误。任何有助于获得多个组件渲染的条件将是一个巨大的帮助 首先构建组件的对象映射:
const Components = {
foo: Foo,
bar: Bar
};
然后使用关键字名称字符串进行访问:
const DynamicComponent = Components[componentName];
<DynamicComponent />
const DynamicComponent=Components[componentName];
在组件中使用地图的快速示例
{definitions.form.map( form => {
const DynamicComponent = Components[form.type];
return <DynamicComponent />
})}
{definitions.form.map(form=>{
常量DynamicComponent=组件[form.type];
返回
})}
首先构建组件的对象映射:
const Components = {
foo: Foo,
bar: Bar
};
然后使用关键字名称字符串进行访问:
const DynamicComponent = Components[componentName];
<DynamicComponent />
const DynamicComponent=Components[componentName];
在组件中使用地图的快速示例
{definitions.form.map( form => {
const DynamicComponent = Components[form.type];
return <DynamicComponent />
})}
{definitions.form.map(form=>{
常量DynamicComponent=组件[form.type];
返回
})}
有了定义类型
数组,剩下的应该有点简单。。。例如,可以使用switch语句。查看代码片段
功能收音机(){
返回
}
函数文本(){
返回
}
函数复选框(){
返回
}
函数App(){
const definitionTypes=['text','checkBox','radio']
返回
{definitionTypes.map(类型=>{
开关(类型){
案例“文本”:
返回
打破
“无线电”案例:
返回
打破
案例“复选框”:
返回
打破
违约:
打破
}})}
}
ReactDOM.render(,document.getElementById('root'))
有了
定义类型
数组,剩下的应该有点简单。。。例如,可以使用switch语句。查看代码片段
功能收音机(){
返回
}
函数文本(){
返回
}
函数复选框(){
返回
}
函数App(){
const definitionTypes=['text','checkBox','radio']
返回
{definitionTypes.map(类型=>{
开关(类型){
案例“文本”:
返回
打破
“无线电”案例:
返回
打破
案例“复选框”:
返回
打破
违约:
打破
}})}
}
ReactDOM.render(,document.getElementById('root'))