在寫(xiě)react mobx的demo時(shí),給checkbox 添加一個(gè)onChange事件,并且忘記在constructor中bind事件,導(dǎo)致this指向錯(cuò)誤
import React from 'react'
import { observer } from 'mobx-react'
@observer
class Todo extends React.Component {
constructor(props){
super(props);
// this.toggleFinished = this.toggleFinished.bind(this)
// this.removeTodo = this.removeTodo.bind(this)
}
toggleFinished() {
console.log(this) // undefined,因?yàn)椴](méi)有綁定this
const todo = this.props.todo;
todo.finished = !todo.finished
}
removeTodo = () => {
const i = this.props.i;
// const AppState = this.props.AppState;
this.props.AppState.todoList.splice(i,1)
}
render(){
const todo = this.props.todo;
return (
<li>
<input type="checkbox" checked={todo.finished} onChange={this.toggleFinished} />
id:{todo.id},task:{todo.task},finished:{todo.finished?'true':'false'}
<button onClick={this.removeTodo}>remove it</button>
</li>
)
}
}
export default Todo

image.png
報(bào)錯(cuò)原因: this并沒(méi)有綁定到Todo上
官方文檔React處理事件中這么解釋:在JSX回調(diào)中你必須注意 this 的指向。 在 JavaScript 中,類方法默認(rèn)沒(méi)有 綁定 的。如果你忘記綁定 this.handleClick 并將其傳遞給onClick,那么在直接調(diào)用該函數(shù)時(shí),this 會(huì)是 undefined 。
解決方法:
1.在constructor中綁定this
constructor(props){
super(props);
this.toggleFinished = this.toggleFinished.bind(this) // 將this綁定到當(dāng)前對(duì)象
// this.removeTodo = this.removeTodo.bind(this)
}
2.使用箭頭函數(shù) ()=>
toggleFinished =() =>{
console.log(this) // Todo...
// const todo = this.props.todo;
// todo.finished = !todo.finished
}
箭頭函數(shù)() this指向
MDN解釋:在箭頭函數(shù)中,this與封閉詞法上下文的this保持一致。在全局代碼中,它將被設(shè)置為全局對(duì)象。
在本章中,也就是this指向外層調(diào)用者 Todo