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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值