React propTypes组件类? [英] React propTypes component class?

查看:55
本文介绍了React propTypes组件类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何验证提供的道具是组件类(不是实例)?

How can I validate that the supplied prop is a component class (not instance)?

例如

export default class TimelineWithPicker extends React.PureComponent {

    static propTypes = {
        component: PropTypes.any, // <-- how can I validate that this is a component class (or stateless functional component)?
    };

    render() {
        return (
            <this.props.component {...this.props} start={this.state.start}/>
        );
    }
}

推荐答案

对于使用 PropTypes> = 15.7.0 的任何人,都在其中添加了新的 PropTypes.elementType 拉动请求,并在

For anyone using PropTypes >= 15.7.0 a new PropTypes.elementType was added in this pull request and was released on february 10, 2019.

此prop类型支持所有组件(本机组件,无状态组件,有状态组件,前向引用 React.forwardRef ,上下文提供者/消费者).

This prop type supports all components (native components, stateless components, stateful components, forward refs React.forwardRef, context providers/consumers).

当不是这些元素中的任何一个时,它会发出警告;当传递的prop是元素( PropTypes.element )而不是类型时,它也会引发警告.

And it throws a warning when is not any of those elements, it also throws a warning when the prop passed is an element (PropTypes.element) and not a type.

最后,您可以像使用其他道具类型一样使用它:

Finally you can use it like any other prop type:

const propTypes = {
    component: PropTypes.elementType,
    requiredComponent: PropTypes.elementType.isRequired,
};

这篇关于React propTypes组件类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆