react里面的this_React 中 this指向问题
在寫react mobx的demo時,給checkbox 添加一個onChange事件,并且忘記在constructor中bind事件,導致this指向錯誤
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,因為并沒有綁定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 (
id:{todo.id},task:{todo.task},finished:{todo.finished?'true':'false'}
remove it
)
}
}
export default Todo
image.png
報錯原因: this并沒有綁定到Todo上
官方文檔React處理事件中這么解釋:在JSX回調中你必須注意 this 的指向。 在 JavaScript 中,類方法默認沒有 綁定 的。如果你忘記綁定 this.handleClick 并將其傳遞給onClick,那么在直接調用該函數時,this 會是 undefined 。
解決方法:
1.在constructor中綁定this
constructor(props){
super(props);
this.toggleFinished = this.toggleFinished.bind(this) // 將this綁定到當前對象
// this.removeTodo = this.removeTodo.bind(this)
}
2.使用箭頭函數 ()=>
toggleFinished =() =>{
console.log(this) // Todo...
// const todo = this.props.todo;
// todo.finished = !todo.finished
}
箭頭函數() this指向
MDN解釋:在箭頭函數中,this與封閉詞法上下文的this保持一致。在全局代碼中,它將被設置為全局對象。
在本章中,也就是this指向外層調用者 Todo
總結
以上是生活随笔為你收集整理的react里面的this_React 中 this指向问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css div里引用em字体会变斜体_前
- 下一篇: 天锋w2019_不知道为什么那么多人喜欢