问题描述
我在 React 中表现一般,但我必须构建一个使用 JSON 呈现表单的程序。 JSON 是这样的:
{
id:"section_id",elemtype:"section",inner_elements:[
{ id:"row_id",elemtype:"row",inner_elements:[
{ id:"col1_id",elemtype:"column",inner_elements:[
{ id:"text4_id",elemtype:"textBox",inner_elements:[],style:{} }
],style:{},classes:{},w:0},{ id:"col2_id",inner_elements:[
{ id:"text1_id",w:0,style:{} },{ id:"text2_id",{ id:"text3_id",style:{} }
],{ id:"row2_id",{ id:"row_3id",style:{} }
],style:{}
}
现在我想使用递归和开关来实现这一点,而不是使用 if-else,我想要单个组件,它可以注入其他组件并可以使用递归渲染具有嵌套元素(子项)的结构。
这是我的想法,但它不起作用......
import React from 'react'
import ROW from '../../components/FormComponents/ROW'
import COLUMN from '../../components/FormComponents/COLUMN'
import TextBox from '../../components/FormComponents/TextBox'
const FormElem =(props)=> {
console.log('props :: '+JSON.stringify(props));
const elemType = props.elemtype;
console.log('elemType :: '+elemType);
const ELEMENT = () => {
switch(elemType){
case 'row':
console.log('setting row element');
return <ROW id={props.id} />
break;
case 'column':
console.log('setting column element');
return <COLUMN id={props.id} />
break;
case 'textBox':
console.log('setting textBox element');
return <TextBox id={props.id} />
break;
default:
console.log('not matched with any');
return (
<div>
NOT FOUND!
</div>
);
break;
}
}
return (
<ELEMENT>
{
props.inner_elements.length>0
?
props.inner_elements.map(
(elem,index) => {
console.log('elem :: '+JSON.stringify(elem));
<ELEMENT id={props.id} elemtype={props.elemtype} inner_elements={elem}/>
}
)
:
<ELEMENT id={props.id} elemtype={props.elemtype}/>
}
</ELEMENT>
)
}
export default FormElem
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)