遍历 JSON 并创建 React 组件

Traverse through JSON and create React components

如何遍历我的数据结构并创建 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 元素时我遇到了麻烦。

您可以创建一个调用自身的函数。

示例

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>
  )
}

您可以按照下面的示例进行操作: 假设您的 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:
           //..../
    }
};