Reactjs 用于接受组件作为道具的道具类型?
在这个人为的例子中,Reactjs 用于接受组件作为道具的道具类型?,reactjs,Reactjs,在这个人为的例子中,componentType的最佳定义是什么 const componentType = PropTypes.oneOfType([ PropTypes.shape({render: PropTypes.func.isRequired}), // React.createClass / React.Component ...better way to describe? PropTypes.func,
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 />
);
}
});
而我想要的东西看起来像:
<Selector components={[ThingA, ThingB]} />
我想传递类型,而不是实例。您正在寻找
数组和元素的组合。可以在文档页面上找到PropType列表
我希望它看起来像这样:
<Selector components={[<ThingA />, <ThingB />]} />
components: React.PropTypes.arrayOf(React.PropTypes.element)
我交叉发布到github,并得到了一个。因此,它应该是:
const componentType = PropTypes.oneOfType([PropTypes.string, PropTypes.func])
func
涵盖了“经典”react组件、ES6类和无状态函数组件的类型<代码>字符串
涵盖本机元素的大小写(例如“div”)。react router就是这样处理的:
这似乎是最新的:
TLDR
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
};
const propTypes = {
component: PropTypes.elementType,
requiredComponent: PropTypes.elementType.isRequired,
};