React绑定this的三种方式
轉載自??React綁定this的三種方式
React可以使用React.createClass、ES6 classes、純函數3種方式構建組件。使用React.createClass會自動綁定每個方法的this到當前組件,但使用ES6 classes或純函數時,就要靠手動綁定this了。接下來介紹React中三種綁定this的方法
bind()
Function.prototype.bind(thisArg [, arg1 [, arg2, …]])?是ES5新增的函數擴展方法,bind()返回一個新的函數對象,該函數的this被綁定到thisArg上,并向事件處理器中傳入參數
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(或其他對象)后面的參數,之后它們會被插入到目標函數的參數列表的開始位置,傳遞給綁定函數的參數會跟在它們的后面。
構造函數內綁定
在構造函數?constructor?內綁定this,好處是僅需要綁定一次,避免每次渲染時都要重新綁定,函數在別處復用時也無需再次綁定
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>)} }箭頭函數
箭頭函數則會捕獲其所在上下文的this值,作為自己的this值,使用箭頭函數就不用擔心函數內的this不是指向組件內部了。可以按下面這種方式使用箭頭函數:
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>)} }這種方式有個小問題,因為箭頭函數總是匿名的,如果你打算移除監聽事件,可以改用以下方式:
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>)} }三種方法都能實現this的綁定,至于用哪種方式還跟著自己的習慣來。
》》 更多干貨 》》
參考
-
MDN文檔 Function.prototype.bind()
-
MDN穩定 Arrow Functions
總結
以上是生活随笔為你收集整理的React绑定this的三种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在MySQL的InnoDB存储引擎中co
- 下一篇: 浅谈流处理算法 (1) – 蓄水池采样