ReactJS将道具转移到动态组件

时间:2016-12-23 17:09:27

标签: reactjs react-jsx

目前我已经构建了一个非常简单的工厂,它查看JSON配置并使用它来为该组件动态生成组件和适当的道具:

let exampleJSON = {
  "components": [
    {
      "type":"ComponentA",
      "params": { myProp: "hey there"  }
    },
    {
      "type":"ComponentB",
      "params": { myOtherProp: "Yo"  }
    }
  ]
}

const ComponentA = (props) => {
  let { myProp } = props;
  return  (
    <div>{ myProp }</div>
  )
}

const ComponentB = (props) => {
  let { myOtherProp } = props;
  return  (
    <div>{ myOtherProp }</div>
  )
}

const ComponentFactory = (props) => {
  const { content } = props;
  return (
    <div>
      { 
        content.components.map( (component, index) => {
          console.log(component);
          let Component = "" + component.type;
          return (
            <Component key={ index } {...component.params } />
          )
        })
       }
    </div>
  )
};

ReactDOM.render(
  <ComponentFactory content={ exampleJSON } />,
  document.getElementById('root')
);

示例:http://codepen.io/jimhill/pen/LboGEY

但是,每当我运行此操作时,我都会收到错误Unknown prop myProp on <ComponentA> tag。如果我手动创建它,但我没有收到此错误。

有什么想法吗?

编辑:如果我在对象中定义元素并通过键引用它们,这很好。

import { render } from 'react-dom';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';

const components = {
    'ComponentA': ComponentA,
    'ComponentB': ComponentB
}

const TheFactory = (props) => {
    let Component = components[props.componentType];
    return (
        <div>
            <Component { ...props.componentProps } />
        <div>
    )
}

render(
    <TheFactory componentType="ComponentA" componentProps={ SomeProp:"An example" } />,
    document.getElementById('root')
);

1 个答案:

答案 0 :(得分:5)

以下内容与您尝试实现的内容类似吗?

const ComponentA = (props) => {
    let { myProp } = props;
    return  (
        <div>{ myProp }</div>
    )
}

const ComponentB = (props) => {
    let { myOtherProp } = props;
    return  (
        <div>{ myOtherProp }</div>
    )
}

let exampleJSON = {
    "components": [
        {
            "type": ComponentA,
            "params": { myProp: "hey there"  }
        },
        {
            "type": ComponentB,
            "params": { myOtherProp: "Yo..."  }
        }
    ]
}

const ComponentFactory = (props) => {
    const { content } = props;
    return (
        <div>
            { 
                content.components.map( (component, index) => {
                    let Component = component.type;
                    return (
                        <Component key={ index } {...component.params } />
                    )
                })
            }
        </div>
    )
};

ReactDOM.render(
    <ComponentFactory content={ exampleJSON } />,
document.getElementById('root')
);