溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

在React中綁定this作用域并傳參的解決方法

發(fā)布時間:2020-08-19 10:09:33 來源:億速云 閱讀:313 作者:小新 欄目:開發(fā)技術

這篇文章給大家分享的是有關在React中綁定this作用域并傳參的解決方法的內容。小編覺得挺實用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。

在React中時常會遇到this指向的作用域問題 從而導致undefined報錯

先來個Demo:
功能很簡單 點擊按鈕改變文字

import React from 'react';

export default class BindWithThis extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      msg:"BindWithThis"
    }
  }

  render() { 
    return <div>
      <input type="button" value="Way1" onClick={this.changeMsg1}/>
      <hr/>
      <h4>{this.state.msg}</h4>
    </div>
  }

  changeMsg1(){
    console.log(this)
    this.setState({
      msg:"Way1"
    })
  }
}

但會遇到問題:Cannot read property ‘setState' of undefined

在React中綁定this作用域并傳參的解決方法

這是因為 在changeMsg1方法內部的this指向的并不是外面的組件 因而根本就不會有setState()方法了 自然會報錯

為此 有三種解決方法

方式一:在事件處理函數(shù)中使用.bind()

只要這樣即可:

render() { 
    return <div>
      <input type="button" value="Way1" onClick={this.changeMsg1.bind(this)}/>
      <hr/>
      <h4>{this.state.msg}</h4>
    </div>
  }

bind()的作用是為前面的函數(shù)修改函數(shù)內部的this的指向 從而使得函數(shù)內部的this指向bind中的第一個參數(shù)

bind()還可以傳值:
bind第一個參數(shù)后面的所有參數(shù)都會作為調用bind前面的函數(shù)的參數(shù)傳遞

render() { 
  return <div>
    <input type="button" value="Way1" onClick={this.changeMsg1.bind(this,"壹","貳")}/>
    <hr/>
    <h4>{this.state.msg}</h4>
  </div>
}

changeMsg1(arg1,arg2){
  this.setState({
    msg:"Way1"+arg1+arg2
  })
}

除了bind()之外 還有call()和apply() 它們都能改變函數(shù)內部的this的指向
不過bind()和call()/apply()的區(qū)別是:bind()并不會立即調用 而call()/apply()會立即調用

方式二:在構造函數(shù)中使用.bind()

當為一個函數(shù)調用bind 從而改變this的指向之后 bind函數(shù)的返回值是這個被改變this指向的函數(shù)的改變后的引用
bind并不會修改原函數(shù)的this的指向 而是返回一個修改后的函數(shù)的指向 因此需要重新接收方可生效

import React from 'react';

export default class BindWithThis extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      msg:"BindWithThis"
    }

    // 當為一個函數(shù)調用bind 改變this的指向之后 bind函數(shù)的返回值是這個被改變this指向的函數(shù)的改變后的引用 因此需要重新接收
    this.changeMsg2 = this.changeMsg2.bind(this,"壹","貳")
  }

  render() { 
    return <div>
      <input type="button" value="Way2" onClick={this.changeMsg2}/>
      <hr/>
      <h4>{this.state.msg}</h4>
    </div>
  }

  changeMsg2(arg1,arg2){
    this.setState({
      msg:"Way2"+arg1+arg2
    })
  }
}

方式三:使用箭頭函數(shù)

利用了箭頭函數(shù)的特性:箭頭函數(shù)內部的this永遠指向調用者方的this

render() { 
  return <div>
    <input type="button" value="Way3" onClick={() => {this.changeMsg3("壹","貳")}}/>
    <hr/>
    <h4>{this.state.msg}</h4>
  </div>
}

changeMsg3 = (arg1,arg2) => {
  this.setState({
    msg:"Way3"+arg1+arg2
  })
}

當然 更推薦使用更加方便的箭頭函數(shù)

感謝各位的閱讀!關于在React中綁定this作用域并傳參的解決方法就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI