寫在開頭:下面部分內(nèi)容是轉(zhuǎn)自其他大佬的解釋勋陪,本文只是轉(zhuǎn)摘+整理硫兰,供自己學習記錄。
1违孝、關于react學習中的this
首先解釋js中的this調(diào)用時可能出現(xiàn)bug的情況——原理:JS中的this是由函數(shù)調(diào)用的地方所決定的泳赋。例1:
上面的例子中,第一個this指的是cat(即當前函數(shù)所在的對象)校坑;而輸出結(jié)果則是undefined(ES6的語法下默認自動使用嚴格模式千诬,即‘use strict;’;如果非嚴格模式輸出結(jié)果為window)
js在對象外時徐绑,函數(shù)被賦給tom時,當前對象不為cat毅访,this則指向了undefine盘榨。
解決this指向的問題的方法:
如果沒有this,則不需要用下面兩種方法较曼。react中不用bind(this)是為了提高效率。
1弛饭、箭頭函數(shù)
class A entend Component {
? ? onChange = (value) => {
? ? ? ? console.log(this); ........
????}
? ? render(
? ? ? ? <Button onChange = "this.onChange" />
????)
}
2、bind(this)
class A extend Component{
? ? onChange(value) {console.log()........}? // onChange函數(shù)
????render中 調(diào)用時this.onChange.bind(this, value);
}
3档桃、在constructor內(nèi)提前將綁定了bind的函數(shù)賦給新變量 ? => 其實和方法一類似
contructor (prop) {
? ? .......(其他內(nèi)容) ? this.onChange= this.onChange.bind(this);
}
onChange = (value) => {
? ? ? ? console.log(this); ........
????}
render(
? ? <Button onChange = "this.onChange" />
)