javascript - React - 从 json 动态渲染组件
问题描述
我正在尝试从这样的 JSON 渲染组件:
const element = [
{
"component" : "container",
"children" : [
{
"component" : "text",
"content" : "foo"
},
{
"component" : "text",
"content" : "bar"
},
]
}
]
代码很简单,但我不知道为什么容器显示为空。
const allComponents = {
text: (p) => {return <p>text</p>;},
container: (p) => {return <div className='container'>{p.children}</div>;}
};
function decoder(element) {
const el = element.component;
if (typeof allComponents[el] !== "undefined") {
const Comp = allComponents[el];
console.log('Decoding: ' + el);
return (
<Comp>
{element.children && (
element.children.map(child => {decoder(child)})
)}
</Comp>
)
}
}
export default decoder;
容器返回空,如果我记录p.children
输出是一个未定义对象的数组。任何的想法 ?
解决方案
你decoder
必须像 a 一样使用react component
,所以:
- 它应该以 开头
capital case
,即:Decoder
。 - 它应该始终
return something
:return null
像 else 一样添加到未定义的检查中。 - 什么时候
mapping on children
,你must return something
(你实际上只是在执行解码器函数而不是返回)。
总结:
function Decoder({ element }) {
const el = element.component;
if (typeof allComponents[el] !== "undefined") {
const Comp = allComponents[el];
console.log("Decoding: " + el);
return (
<Comp>
{element.children &&
element.children.map(child => <Decoder element={child} />)}
</Comp>
);
}
return null;
}
PS:你需要一个内部解码器的密钥
这是一个工作沙箱
编辑
要显示您的文本内容,您需要文本组件支持它,然后您将其作为道具传递给 Comp 渲染,如沙箱中所示。
推荐阅读
- python - 来自社交媒体的文本聚类
- c++ - TCP 缓冲区的解析器
- python - 使用python将内容从xlsx复制到记事本
- c# - C# SqlBulkCopy 错过了一行
- c# - 以编程方式更改面板的背景颜色
- wordpress - 没有找到与 Woocommerce 产品变体请求中的 URL 匹配的路由?
- python - 从 Visual Studio C++ 解决方案调用 Python 脚本
- angular - 为什么 Visual Studio 2017 Dot Net core 2.1 和 Angular 模板中不存在 WebPack?
- reactjs - React PropTypes 不直接传输
- corda - 如何部署corda-finance-3.1-corda.jar?