Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript “如何动态创建”;“汇编”;在没有babel的情况下快速反应组件?_Javascript_Reactjs_React Native - Fatal编程技术网

Javascript “如何动态创建”;“汇编”;在没有babel的情况下快速反应组件?

Javascript “如何动态创建”;“汇编”;在没有babel的情况下快速反应组件?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,如果我有一个嵌套的节点对象,比如(忽略语法): 有没有可能在我的React原生应用程序的JS中动态动态地创建一个嵌套的“已编译”React元素,而不使用babel,比如: function el() { return React.createElement( Svg, { height: "40", width: "40", viewBox: "0 0 22 22" }, React.createElement( G, null,

如果我有一个嵌套的节点对象,比如(忽略语法):

有没有可能在我的React原生应用程序的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" }
      )
    )
  );
};

你想做那样的事吗

function createNodeElement(node) {
  return React.createElement(
    node.name,
    node.attrs,
    node.children && node.children.map(el => createNodeElement(el)),
  )
}

如果答案不能满足您的需要,我们可以讨论更多。

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

为什么不创建一个只呈现数据结构的组件呢?不知道。也许这就是我需要做的?也许我想得太多了?你能给我一些建议吗?哇,这比我刚想到的更简单,只需要根据我的示例创建可能节点类型的映射,然后执行
类型[node.name]
render() {
  return jsonToComponent(props.json);
}