props
的值能够正常首收到, 以下代码能够正常运行class Person {
static propTypes = {
age: PropTypes.number
}
static defaultProps = {
age: 18
}
}
ReactDOM.render(<Person/>, document.getElmentById('test'))
constructor
值也能正常收到,以下代码也能够正常运行class Person {
constructor(props) {
super(props)
console.log(props)
}
static propTypes = {
age: PropTypes.number
}
static defaultProps = {
age: 18
}
}
ReactDOM.render(<Person/>, document.getElmentById('test'))
React
中,构造函数仅适用于以下两种情况class Person extends React.Component {
constructor() {
// 初始化状态
this.state = {key: value}
// 解决 fun this 指向的问题
this.fun = this.fun.bind(this)
}
...
}
constructor
构造器中写的,以下代码是简写形式,赋值语句的写法class Person extends React.Component {
state = {key: value}
fun = () => {}
...
}
props
参数,并且通过 super
传递到他的父类,否则可能会出现以下的 bug
constructor
构造函数, 但是没有接收 props
参数,并且也没有通过 super
触底到父类,就会出现 undefined
constructor
没有接收 props
class Person {
constructor() {
super()
console.log(this.props) // undefined
}
...
}
constructor
接收 props
class Person extends React.Component {
constructor(props) {
super(props)
console.log(this.props) // 实例对象上的 props
}
...
}
构造器 constructor
是否接收 props
,是否传递给 super
,取决于:是否要在构造器中通过 this
访问 props
, 在开发的时候基本上是用不到构造器的