React 中 this指向问题

在写react mobx的demo时,给checkbox 添加一个onChange事件,并且忘记在constructorbind事件,导致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 (
        <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

报错原因: 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容