React-010-事件處理函數(shù)的this指向問題,區(qū)分普通函數(shù)與事件處理函數(shù) 1、普通函數(shù)是直接調(diào)用的。不存在 this 指向問題,誰調(diào)用的,this 指向就是誰。 2、普通函數(shù)沒有事件對象 event 3、事件處理函數(shù)其實也是一個函數(shù),只是他綁定在某個事件上。 4、事件處理函數(shù)的 this 默認指向 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)一進行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 4、PureComponent 。它會幫助我們計算子組件接收到的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 = () => { ... } // 這種方式同樣也推薦。 |
|