React事件绑定几种方法测试
前提
es6寫法的類方法默認(rèn)沒有綁定this,不手動(dòng)綁定this值為undefined。
因此討論以下幾種綁定方式。
一、構(gòu)造函數(shù)constructor中用bind綁定
class App extends Component {constructor (props) {super(props)this.state = {t: 't'}// this.bind1 = this.bind1.bind(this) 無參寫法this.bind1 = this.bind1.bind(this, this.state.t)}// 無參寫法 // bind1 () {// console.log('bind1', this)// }bind1 (t, event) {console.log('bind1', this, t, event)}render () {return (<div><button onClick={this.bind1}>打印1</button></div>)} }二、在調(diào)用的時(shí)候使用bind綁定this
bind2 (t, event) {console.log('bind2', this, t, event)}render () {return (<div><button onClick={this.bind2.bind(this, this.state.t)}>打印2</button></div>)} // 無參寫法同第一種三、在調(diào)用的時(shí)候使用箭頭函數(shù)綁定this
bind3 (t, event) {console.log('bind3', this, t, event)}render () {return (<div>// <button onClick={() => this.bind3()}>打印3</button> 無參寫法<button onClick={(event) => this.bind3(this.state.t, event)}>打印3</button></div>)}四、使用屬性初始化器語法綁定this
bind4 = () =>{console.log('bind4', this)}render () {return (<div><button onClick={this.bind4}>打印4</button>// 帶參需要使用第三種方法包一層箭頭函數(shù)</div>)}附加::方法(不能帶參,stage 0草案中提供了一個(gè)便捷的方案——雙冒號(hào)語法)
bind5(){console.log('bind5', this)}render() {return (<div><button onClick={::this.bind5}></button></div>)}方法一優(yōu)缺點(diǎn)
優(yōu)點(diǎn):
只會(huì)生成一個(gè)方法實(shí)例;
并且綁定一次之后如果多次用到這個(gè)方法也不需要再綁定。
缺點(diǎn):
即使不用到state,也需要添加類構(gòu)造函數(shù)來綁定this,代碼量多;
添加參數(shù)要在構(gòu)造函數(shù)中bind時(shí)指定,不在render中。
方法二、三優(yōu)缺點(diǎn)
優(yōu)點(diǎn):
寫法比較簡單,當(dāng)組件中沒有state的時(shí)候就不需要添加類構(gòu)造函數(shù)來綁定this。
缺點(diǎn):
每一次調(diào)用的時(shí)候都會(huì)生成一個(gè)新的方法實(shí)例,因此對(duì)性能有影響;
當(dāng)這個(gè)函數(shù)作為屬性值傳入低階組件的時(shí)候,這些組件可能會(huì)進(jìn)行額外的重新渲染,因?yàn)槊恳淮味际切碌姆椒▽?shí)例作為的新的屬性傳遞。
方法四優(yōu)缺點(diǎn)
優(yōu)點(diǎn):
創(chuàng)建方法就綁定this,不需要在類構(gòu)造函數(shù)中綁定,調(diào)用的時(shí)候不需要再作綁定;
結(jié)合了方法一、二、三的優(yōu)點(diǎn)。
缺點(diǎn):
帶參就會(huì)和方法三相同,這樣代碼量就會(huì)比方法三多了。
總結(jié)
方法一是官方推薦的綁定方式,也是性能最好的方式。
方法二和方法三會(huì)有性能影響,并且當(dāng)方法作為屬性傳遞給子組件的時(shí)候會(huì)引起重新渲染問題。
方法四和附加方法不做評(píng)論。
大家根據(jù)是否需要傳參和具體情況選擇適合自己的方法就好。
謝謝閱讀。
更多專業(yè)前端知識(shí),請(qǐng)上 【猿2048】www.mk2048.com
總結(jié)
以上是生活随笔為你收集整理的React事件绑定几种方法测试的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jsp实现上一页下一页翻页功能
- 下一篇: webpack常用loader和plug