【问题标题】:Traverse through JSON and create React components遍历 JSON 并创建 React 组件
【发布时间】:2018-06-29 16:09:05
【问题描述】:

如何遍历我的数据结构并创建 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 元素是我碰壁的地方。

【问题讨论】:

  • 你尝试了什么,你有代码给我们看吗?

标签: json reactjs react-native traversal


【解决方案1】:

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

示例

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

【讨论】:

  • 这是否支持,例如 10 级嵌套组件?
  • @Dan 是的,因为只要该组件中有一个子数组,它就会调用该函数
  • 老兄,绝对的传奇!
【解决方案2】:

您可以执行以下示例: 假设您的 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:
           //..../
    }
};

【讨论】:

    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2016-10-30
    • 2019-09-29
    • 2018-07-17
    • 1970-01-01
    相关资源
    最近更新 更多