我在 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", elemtype:"column", inner_elements:[
{ id:"text1_id", elemtype:"textbox", inner_elements:[], style:{} }
], w:0, style:{} },
{ id:"text2_id", elemtype:"textbox", inner_elements:[], style:{} },
{ id:"text3_id", elemtype:"textbox", inner_elements:[], style:{} }
], w:0, style:{} },
{ id:"row2_id", elemtype:"row", inner_elements:[], style:{} },
{ id:"row_3id", elemtype:"row", inner_elements:[], 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