给出这个人为的示例,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]} />
我想传递类型,而不是实例。
我交叉张贴到github并获得了this answer。所以应该是:
const componentType = PropTypes.oneOfType([PropTypes.string, PropTypes.func])
func
涵盖了来自“经典”反应组件,ES6类和无状态功能组件的类型。 string
涵盖了本机元素的大小写(例如“ div”)。
这是反应路由器如何处理它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
};
您正在寻找arrayOf
和element
的组合。 propType的列表可以在文档的Reusable Components页面上找到。
我希望它看起来像这样:
components: React.PropTypes.arrayOf(React.PropTypes.element)