首页 > 解决方案 > 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输出是一个未定义对象的数组。任何的想法 ?

标签: javascriptjsonreactjs

解决方案


decoder必须像 a 一样使用react component,所以:

  • 它应该以 开头capital case,即:Decoder
  • 它应该始终return somethingreturn 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 渲染,如沙箱中所示。


推荐阅读