将组件作为道具传递给另一个组件

时间:2019-01-16 09:46:51

标签: javascript reactjs

我正在尝试创建“ AB测试”组件:

import React from 'react';
import PropTypes from 'prop-types';

const AbTest = ({ components, criteriaToMatch }) => {
  let componentToRender;

  components.forEach((component) => {
    if (component.criteria === criteriaToMatch) {
      componentToRender = component.instance;
    }
  });

  return componentToRender;
};

AbTest.propTypes = {
  components: PropTypes.arrayOf(PropTypes.shape({
    instance: PropTypes.func,
    criteria: PropTypes.any,
  })),
  criteriaToMatch: PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.string,
    PropTypes.number,
  ]),
};

export default AbTest;

然后您将像这样使用它:

import MyComponentA from '../my-component-a';
import MyComponentB from '../my-component-b';

<AbTest
  components={[
    { instance: MyComponentA, criteria: 'A' },
    { instance: MyComponentB, criteria: 'B' },
  ]}
  criteriaToMatch="A"
/>

因此,您将为它传递一个组件数组,每个组件都有一些条件,并且会匹配任何匹配的元素。但我收到一个错误消息:

  

函数作为React子元素无效

1 个答案:

答案 0 :(得分:2)

对于AbTest组件,您必须返回类似该组件的实例

const AbTest = ({ components, criteriaToMatch }) => {
  let ComponentToRender;

  components.forEach((component) => {
    if (component.criteria === criteriaToMatch) {
      ComponentToRender = component.instance;
    }
  });

  return <ComponentToRender />;
};
相关问题