我正在尝试在我的组件上设置一些类型验证,但是没有一种类型检查似乎正在工作。如果我像这样使用ES6类表示法:
import React from "react";
import PropTypes from 'prop-types';
export default class MyComponent extends React.Component {
constructor(props) {
super(props);
}
static defaultProps = {
IdoNotExist: PropTypes.element.isRequired
}
render() {
return (
<div></div>
);
}
}
我的控制台中没有出现任何警告。
我也在DEV模式(非生产)工作,我也试过这样做:
MyComponent.defaultProps = {
IdoNotExist:PropTypes.element.isRequired
}
似乎没有任何作用:(
旁注:是否有可能在做出更多“更难”的类型检查?当proptype检查失败时,我不仅仅想要'警告'。我想抛出一个异常,并且不会调用'render'函数。是否可以做出反应?
答案 0 :(得分:2)
您正在使用defaultProps
属性,但这只会初始化道具值。要进行验证,请在组件上使用propTypes
属性。显然,您将这两个属性混为一谈,并且您正在使用defaultProps
,propTypes
应该定义。