1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > react里面的this_React 中 this指向问题

react里面的this_React 中 this指向问题

时间:2019-10-22 06:35:55

相关推荐

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 ponent {

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。