React 中 this指向問(wèn)題

在寫(xiě)react mobx的demo時(shí),給checkbox 添加一個(gè)onChange事件,并且忘記在constructorbind事件,導(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容