在React中时常会遇到this指向的作用域问题 从而导致undefined报错先来个Demo:
功能很简单 点击按钮改变文字
import React from 'react';

export default class BindWithThis extends React.Component {

constructor(props) {

super(props);

this.state = {

msg:"BindWithThis"

}

}


render() {

return







{this.state.msg}





}


changeMsg1(){

console.log(this)

this.setState({

msg:"Way1"

})

}
}

import React from 'react';

export default class BindWithThis extends React.Component {

constructor(props) {

super(props);

this.state = {

msg:"BindWithThis"

}

}


render() {

return







{this.state.msg}





}


changeMsg1(){

console.log(this)

this.setState({

msg:"Way1"

})

}
}
但会遇到问题:Cannot read property ‘setState' of undefined

这是因为 在changeMsg1方法内部的this指向的并不是外面的组件 因而根本就不会有setState()方法了 自然会报错为此 有三种解决方法方式一:在事件处理函数中使用.bind()方式一:在事件处理函数中使用.bind()方式一:在事件处理函数中使用.bind()只要这样即可:
render() {

return







{this.state.msg}





}
render() {

return







{this.state.msg}





}bind()的作用是为前面的函数修改函数内部的this的指向 从而使得函数内部的this指向bind中的第一个参数bind()还可以传值:
bind第一个参数后面的所有参数都会作为调用bind前面的函数的参数传递
render() {

return







{this.state.msg}




}

changeMsg1(arg1,arg2){

this.setState({

msg:"Way1"+arg1+arg2

})
}

render() {

return







{this.state.msg}




}

changeMsg1(arg1,arg2){

this.setState({

msg:"Way1"+arg1+arg2

})
}
除了bind()之外 还有call()和apply() 它们都能改变函数内部的this的指向
不过bind()和call()/apply()的区别是:bind()并不会立即调用 而call()/apply()会立即调用方式二:在构造函数中使用.bind()方式二:在构造函数中使用.bind()方式二:在构造函数中使用.bind()当为一个函数调用bind 从而改变this的指向之后 bind函数的返回值是这个被改变this指向的函数的改变后的引用
bind并不会修改原函数的this的指向 而是返回一个修改后的函数的指向 因此需要重新接收方可生效
import React from 'react';

export default class BindWithThis extends React.Component {

constructor(props) {

super(props);

this.state = {

msg:"BindWithThis"

}


// 当为一个函数调用bind 改变this的指向之后 bind函数的返回值是这个被改变this指向的函数的改变后的引用 因此需要重新接收

this.changeMsg2 = this.changeMsg2.bind(this,"壹","贰")

}


render() {

return







{this.state.msg}





}


changeMsg2(arg1,arg2){

this.setState({

msg:"Way2"+arg1+arg2

})

}
}
import React from 'react';

export default class BindWithThis extends React.Component {

constructor(props) {

super(props);

this.state = {

msg:"BindWithThis"

}


// 当为一个函数调用bind 改变this的指向之后 bind函数的返回值是这个被改变this指向的函数的改变后的引用 因此需要重新接收

this.changeMsg2 = this.changeMsg2.bind(this,"壹","贰")

}


render() {

return







{this.state.msg}





}


changeMsg2(arg1,arg2){

this.setState({

msg:"Way2"+arg1+arg2

})

}
}方式三:使用箭头函数方式三:使用箭头函数方式三:使用箭头函数利用了箭头函数的特性:箭头函数内部的this永远指向调用者方的this
render() {

return


{this.changeMsg3("壹","贰")}}/>




{this.state.msg}




}

changeMsg3 = (arg1,arg2) => {

this.setState({

msg:"Way3"+arg1+arg2

})
}

render() {

return


{this.changeMsg3("壹","贰")}}/>




{this.state.msg}




}

changeMsg3 = (arg1,arg2) => {

this.setState({

msg:"Way3"+arg1+arg2

})
}
当然 更推荐使用更加方便的箭头函数