如果我有一个嵌套的节点对象,就像这样(忽略语法):
const el = {
node: {
name: 'Svg',
attrs: { height: "40", width: "40", viewBox: "0 0 22 22" },
children: [
{
node: {
name: 'G',
attrs: null,
children: [
{
node: {
name: 'Path',
attrs: { d: "M15.39,1c0.107" },
children: nullm
}
}
]
}
}
]
}
};
有没有可能在我的React Native应用程序的JS中动态地动态创建一个嵌套的“编译的”React元素,而不使用babel,比如:
function el() {
return React.createElement(
Svg,
{ height: "40", width: "40", viewBox: "0 0 22 22" },
React.createElement(
G,
null,
React.createElement(
Path,
{ d: "M15.39,1c0.107" }
)
)
);
};
发布于 2017-11-04 20:51:19
你想做这样的事情吗?
function createNodeElement(node) {
return React.createElement(
node.name,
node.attrs,
node.children && node.children.map(el => createNodeElement(el)),
)
}
如果答案不能满足您的需求,我们可以讨论更多。
发布于 2017-11-04 20:52:32
@lumio修正了我的课程,我只需要渲染js数据结构。因此,使用以下js:
const json = {
type: 'Svg',
props: {
height: 170,
viewBox: '0 0 100 170',
width: 100,
},
children: [
{
type: 'Path',
props: {
d: 'M100 0H50v85l50-85z',
fill: '#0f0',
},
},
{
type: 'Path',
props: {
d: 'M0 170h50V85L0 170z',
fill: '#a0f',
},
},
],
};
和以下组件:
const types = { Svg, Path };
const jsonToComponent = (obj, key) => {
const El = types[obj.type];
const children = obj.children ? obj.children.map(jsonToComponent) : [];
return (
<El
key={key}
{...obj.props}
>
{children}
</El>
);
};
我可以在另一个虚拟组件中呈现它:
render() {
return jsonToComponent(props.json);
}
https://stackoverflow.com/questions/47109538
复制相似问题