React绑定this的三种方式
轉(zhuǎn)載自??React綁定this的三種方式
React可以使用React.createClass、ES6 classes、純函數(shù)3種方式構(gòu)建組件。使用React.createClass會自動綁定每個方法的this到當(dāng)前組件,但使用ES6 classes或純函數(shù)時,就要靠手動綁定this了。接下來介紹React中三種綁定this的方法
bind()
Function.prototype.bind(thisArg [, arg1 [, arg2, …]])?是ES5新增的函數(shù)擴展方法,bind()返回一個新的函數(shù)對象,該函數(shù)的this被綁定到thisArg上,并向事件處理器中傳入?yún)?shù)
import React, {Component} from 'react'class Test extends React.Component {constructor (props) {super(props)this.state = {message: 'Allo!'}}handleClick (name, e) {console.log(this.state.message + name)}render () {return (<div><button onClick={ this.handleClick.bind(this, '趙四') }>Say Hello</button></div>)} }要注意的是,跟在this(或其他對象)后面的參數(shù),之后它們會被插入到目標(biāo)函數(shù)的參數(shù)列表的開始位置,傳遞給綁定函數(shù)的參數(shù)會跟在它們的后面。
構(gòu)造函數(shù)內(nèi)綁定
在構(gòu)造函數(shù)?constructor?內(nèi)綁定this,好處是僅需要綁定一次,避免每次渲染時都要重新綁定,函數(shù)在別處復(fù)用時也無需再次綁定
import React, {Component} from 'react'class Test extends React.Component {constructor (props) {super(props)this.state = {message: 'Allo!'}this.handleClick = this.handleClick.bind(this)}handleClick (e) {console.log(this.state.message)}render () {return (<div><button onClick={ this.handleClick }>Say Hello</button></div>)} }箭頭函數(shù)
箭頭函數(shù)則會捕獲其所在上下文的this值,作為自己的this值,使用箭頭函數(shù)就不用擔(dān)心函數(shù)內(nèi)的this不是指向組件內(nèi)部了。可以按下面這種方式使用箭頭函數(shù):
class Test extends React.Component {constructor (props) {super(props)this.state = {message: 'Allo!'}}handleClick (e) {console.log(this.state.message)}render () {return (<div><button onClick={ ()=>{ this.handleClick() } }>Say Hello</button></div>)} }這種方式有個小問題,因為箭頭函數(shù)總是匿名的,如果你打算移除監(jiān)聽事件,可以改用以下方式:
class Test extends React.Component {constructor (props) {super(props)this.state = {message: 'Allo!'}}handleClick = (e) => {console.log(this.state.message)}render () {return (<div><button onClick={ this.handleClick }>Say Hello</button></div>)} }不過,在Classes中直接賦值是ES7的寫法,ES6并不支持,只用ES6的話可以用下面寫法:
class Test extends React.Component {constructor (props) {super(props)this.state = {message: 'Allo!'}this.handleClick = (e) => {console.log(this.state.message)}}render () {return (<div><button onClick={ this.handleClick }>Say Hello</button></div>)} }三種方法都能實現(xiàn)this的綁定,至于用哪種方式還跟著自己的習(xí)慣來。
》》 更多干貨 》》
參考
-
MDN文檔 Function.prototype.bind()
-
MDN穩(wěn)定 Arrow Functions
總結(jié)
以上是生活随笔為你收集整理的React绑定this的三种方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在MySQL的InnoDB存储引擎中co
- 下一篇: 浅谈流处理算法 (1) – 蓄水池采样