乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      React-010-事件處理函數(shù)的this指向問題

       好程序員IT 2019-08-09

      React-010-事件處理函數(shù)的this指向問題,區(qū)分普通函數(shù)與事件處理函數(shù)

      1普通函數(shù)是直接調(diào)用的。不存在 this 指向問題,誰調(diào)用的,this 指向就是誰。

      2普通函數(shù)沒有事件對象 event

      3、事件處理函數(shù)其實也是一個函數(shù),只是他綁定在某個事件上。

      4事件處理函數(shù)的 this 默認(rèn)指向 undefined

      解決this指向問題的4種辦法

      1、直接在事件綁定的地方加上 .bind(this)

      <button onClick={this.handleClick.bind(this)}>點我</button>

      2、使用箭頭函數(shù)

      <button

        onClick={event => {

          this.handleClick(event);

        }}

      >

        點我

      </button>

      3、在構(gòu)造函數(shù)中統(tǒng)一進(jìn)行this指向的綁定

        constructor() {

          super();

          this.handleClick = this.handleClick.bind(this);

        }

        render() {

          return (

            <button onClick={this.handleClick}>點我</button>

          )

        }

      4、使用實驗性質(zhì)的 public class fileds 語法。要去使用的話,的需要babel插件的支持.

      1、安裝 @babel/plugin-proposal-class-properties babel 插件

      2 babel 的配置文件中,配置好

      3、從新啟動項目

      class App extends React.Component {

        handleClick = () => {

          console.log(this);

        };

      }

      為啥要使用 bind 來修改this指向,而不能使用 apply、call?

      因為 apply 與 call 他們會直接執(zhí)行函數(shù),而 bind 會返回一個新的函數(shù)。

      在調(diào)用子組件的時候,需要傳遞一個方法下去,這時這個方法的this綁定推薦使用哪幾種:

      推薦使用:在構(gòu)造函數(shù)中的bind 與 public class fileds 語法。

      1、首先要知道的是,父組件render,子組件一定會render

      2我們希望如果子組件沒有發(fā)生變化,那么在 父組件render的時候,讓子組件不做render。節(jié)省性能。

      3、要實現(xiàn)第2點,可以讓子組件繼承的是 PureComponent

      4PureComponent 。它會幫助我們計算子組件接收到的porps 有沒有發(fā)生變化,如果有那么就 render .如果沒有就阻止render

      <Child onFn1={this.handleFn1.bind(this)}  />

      // 由于 .bind() 方法每次都會返回一個新的函數(shù),所以這種方式不推薦。。。。

      <Child onFn1={() => { this.handleFn1() }}  />

      // 由于 每次執(zhí)行到這行代碼,箭頭返回都是一個新的箭頭函數(shù),所以這種方式不推薦

      constructor() {

        super();

        this.handleFn1 = this.handleFn1.bind(this)

      }

      <Child onFn1={this.handleFn1}  />

       // 由于 constructor 構(gòu)造函數(shù)只會執(zhí)行一次,后續(xù)執(zhí)行到 Child 的代碼,傳遞過去的 onFn1 沒有發(fā)生變化

       // 所以這種方式推薦

      <Child onFn1={this.handleFn1}  />

      handleFn1 = () => {

        ...

      }

      // 這種方式同樣也推薦。

        本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多