引用以下内容时报错:
Uncaught TypeError: Cannot read property ‘number’ of undefined
static propTypes = {
value: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
onDecrement: PropTypes.func.isRequired
}
原因及解决:
在之前的版本之中,我们可以通过React.PropTypes这个API访问React内置的一些类型来检查props,在15.5.0版本中,这一API被独立成了一个新的包 prop-types
// 15.4 以前
import React from 'react';
class Component extends React.Component {
render() {
return <div>{this.props.text}</div>;
}
}
Component.propTypes = { text: React.PropTypes.string.isRequired,}
// 15.5 以后
import React from 'react';
import PropTypes from 'prop-types';
class Component extends React.Component {
render() {
return <div>{this.props.text}</div>;
}
}
Component.propTypes = { text: PropTypes.string.isRequired,};
写法:
在组件内部写:
static propTypes = {
value: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
onDecrement: PropTypes.func.isRequired,
onIncrementDoubble: PropTypes.func.isRequired,
onDecrementDoubble: PropTypes.func.isRequired,
incrementAsync: PropTypes.func.isRequired
}
在组件外部写:
ComponentChild.propTypes = {
value: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
onDecrement: PropTypes.func.isRequired,
onIncrementDoubble: PropTypes.func.isRequired,
onDecrementDoubble: PropTypes.func.isRequired,
incrementAsync: PropTypes.func.isRequired
}