propType接受组件作为prop?

问题描述 投票:6回答:3

给出这个人为的示例,componentType的最佳定义是什么?

const componentType = PropTypes.oneOfType([
    PropTypes.shape({render: PropTypes.func.isRequired}), // React.createClass / React.Component ...better way to describe?
    PropTypes.func,                                       // Stateless function
    // others?
]);

const Selector = React.createClass({

    propTypes: {
        components: PropTypes.arrayOf(componentType).isRequired,
        index:      PropTypes.number.isRequired,
    },

    render() {
        const Component = this.props.components[this.props.index];
        return (
            <Component />
        );
    }
});

PropTypes.node不是我要的;它的用法如下所示:

<Selector components={[<ThingA  />, <ThingB  />]} />

而我想要的东西看起来像:

<Selector components={[ThingA, ThingB]} />

我想传递类型,而不是实例。

reactjs
3个回答
8
投票

我交叉张贴到github并获得了this answer。所以应该是:

const componentType = PropTypes.oneOfType([PropTypes.string, PropTypes.func])

func涵盖了来自“经典”反应组件,ES6类和无状态功能组件的类型。 string涵盖了本机元素的大小写(例如“ div”)。


0
投票

这是反应路由器如何处理它here

import React from "react";
import { isValidElementType } from "react-is";

Route.propTypes = {
    children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
    component: (props, propName) => {
      if (props[propName] && !isValidElementType(props[propName])) {
        return new Error(
          `Invalid prop 'component' supplied to 'Route': the prop is not a valid React component`
        );
      }
    },
    exact: PropTypes.bool,
    location: PropTypes.object,
    path: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.arrayOf(PropTypes.string)
    ]),
    render: PropTypes.func,
    sensitive: PropTypes.bool,
    strict: PropTypes.bool
  };

-1
投票

您正在寻找arrayOfelement的组合。 propType的列表可以在文档的Reusable Components页面上找到。

我希望它看起来像这样:

components: React.PropTypes.arrayOf(React.PropTypes.element)
© www.soinside.com 2019 - 2024. All rights reserved.