在React Class中設(shè)置state的初始值或者綁定事件時(shí)
為什么需要在 constructor(){} 中加上 super() 呢
我們嘗試去掉 super() 看看編譯的結(jié)果:
constructor() {
this.state = {searchStr:''};
this.handleChange =this.handleChange.bind(this);
}
運(yùn)行這段代碼時(shí)冈在,會(huì)發(fā)現(xiàn)編譯錯(cuò)誤:
提示沒有在this之前加上super()
其實(shí)就是少了super()倒慧,導(dǎo)致了this的?Reference Error
classMyComponentextendsReact.Component{
constructor() {
console.log(this);// Reference Error
? }
? render() {
return
? }
}
super關(guān)鍵字,它指代父類的實(shí)例(即父類的this對(duì)象)。子類必須在constructor方法中調(diào)用super方法纫谅,否則新建實(shí)例時(shí)會(huì)報(bào)錯(cuò)炫贤。這是因?yàn)樽宇悰]有自己的this對(duì)象,而是繼承父類的this對(duì)象系宜,然后對(duì)其進(jìn)行加工照激。如果不調(diào)用super方法,子類就得不到this對(duì)象盹牧。
正確的姿勢(shì)應(yīng)該是這樣
constructor() {
super();
this.state = {searchStr:''};
this.handleChange =this.handleChange.bind(this);
}
React的官方例子中都是加上了 props 作為參數(shù)
constructor(props) {
super(props);
this.state = {searchStr:''};
this.handleChange =this.handleChange.bind(this);
}
那它們的區(qū)別在哪兒呢
What's the difference between “super()” and “super(props)” in React when using es6 classes?
There is only one reason when one needs to passpropstosuper():
When you want to accessthis.propsin constructor.
(Which is probably redundant since you already have a reference to it.)
意思是說
只有一個(gè)理由需要傳遞props作為super()的參數(shù)俩垃,那就是你需要在構(gòu)造函數(shù)內(nèi)使用this.props
那官方提供學(xué)習(xí)的例子中都是寫成super(props),所以說寫成super(props)是完全沒問題的汰寓,也建議就直接這樣寫