如何遍历数据结构并创建React组件?
{
component: "View",
attributes: {
id: 'main'
},
child: [
{
component: "Text",
content: "Hello World!"
},
{
component: "Link",
attributes: {
href: "#"
},
child: [
{
component: "Text",
content: "Click me!"
}
]
}
]
}
将输出:
<View>
<Text>Hello World!</Text>
<Link>Click me!</Link>
</View>
无论嵌套组件有多少,如何在可行的地方动态地实现这一目标?
我能够制作顶级组件,但是遍历child
元素就是碰到砖墙的地方。
答案 0 :(得分:2)
您可以创建一个调用自身的函数。
样品
parseComponents = (data, key) => {
if (key === undefined || key === null) key = 0;
let Component = null;
switch(data.component) {
case 'View':
Component = View;
break;
case 'Text':
Component = Text;
break;
case 'Link':
Component = Link;
break;
default:
break;
}
if (Component === null) return Component;
return (
<Component key={`${data.component}-${index}`} {...data.attributes}>
{data.child.map((c, index) => this.parseComponents(c, index))}
</Component>
)
}
答案 1 :(得分:0)
您可以按照以下示例进行操作:
假设您的JSON存储在const json
中。
getComponent = (json) => {
if (json.component) {
let children;
if (json.children) {
children = json.children.map(child => this.getComponentEquivalent(child));
}
let Container= this.getComponentEquivalent(json);
return (<Container>{children}</Container>); // as this will return a component you can directly put this in render.
}
};
那么您可能具有可以获取等效组件的功能。
getComponentEquivalent = (object) => {
switch(object.component) {
case "Text":
return <Text>{object.content}</Text>
case "Link"":
return <Link>{object.content}</Link>
//......./
default:
//..../
}
};