![80a4d41ce4c35746f0defa53067fc262.png](https://i-blog.csdnimg.cn/blog_migrate/2df0b6799191c435f4be5cfd4e07f09f.png)
正如标题所述,很多朋友会遇到这么一个疑问:为什么在React组件里,经常会写这样一段代码呢?
constructor(props) {
super(props);
}
用ES6写React组件的时候,大都是先继承Component方法,类似class App extends Component 这样的写法,而组件本身是继承Component的,所以没有this上下文,想要继承父类的上下文,必须执行上述代码,这样才能在constructor中才能使用this上下文。
当然你也可以不写这个构造函数,React在初始化Class后,会将props自动设置到this中,但是在constructor中就不能使用this对象。不过,在组件中还是可以使用类似下面代码
class App extends React.Component {
render() {
return (
<h1>{this.props.title}</h1>
);
}
}
那么又为什么一定要传props这个参数呢?
我顺着在这个思路去找React中Component的源码,如下图所示
![9a7970207173d2188d87597bc1fe4a8b.png](https://i-blog.csdnimg.cn/blog_migrate/f3aa43a8402a94569ad21ac41ce8925b.jpeg)
这才让我恍然大悟super(props)传进来的参数,被Component挂到父类的this上下文上,那么子类继承父类的this上下文,就可以在constructor中使用this.props
总结:
- 调用super的原因:在ES6中,在子类的constructor中必须先调用super才能引用this
- super(props)的目的:在constructor中可以使用this.props