日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

react里面的this_React 中 this指向问题

發布時間:2024/4/11 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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指向问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。