1. 程式人生 > >React ES6元件裡繫結this的三種方式

React ES6元件裡繫結this的三種方式

React可以使用React.createClass、ES6 classes、純函式3種方式構建元件。使用React.createClass會自動繫結每個方法的this到當前元件,但使用ES6 classes或純函式時,就要靠手動繫結this了。

bind(this)

Function.prototype.bind(thisArg [, arg1 [, arg2, …]]) 是ES5新增的函式擴充套件方法,bind()返回一個新的函式物件,該函式的this被繫結到thisArg上,並向事件處理器中傳入引數

import React, {Component} from 'react'
class Greeter extends Component{ constructor (props) { super(props) this.state = {count: 0} } add (v) { this.setState({ count:this.state.count+v }) } render () { return ( <div> <button onClick={this
.add.bind(this,3)}>add</button> </div> ) } }

建構函式內繫結

在建構函式 constructor 內繫結this,好處是僅需要繫結一次,避免每次渲染時都要重新繫結,函式在別處複用時也無需再次繫結

import React, {Component} from 'react'
class Greeter extends Component{
   constructor (props) {
        super(props)
        this.state = {count
: 0} this.add=this.add.bind(this) } add () { this.setState({ count:this.state.count+1 }) } render () { return ( <div> <button onClick={this.add}>add</button> </div> ) } }

箭頭函式

箭頭函式則會捕獲其所在上下文的this值,作為自己的this值

1:

import React, {Component} from 'react'
class Greeter extends Component{
   constructor (props) {
        super(props)
        this.state = {count: 0}
    }

    add () {
        this.setState({
           count:this.state.count+1
        })
    }

    render () {
        return (
            <div>
                <button onClick={()=>{this.add()}}>add</button>
            </div>
        )
    }
}

2:

在Classes中直接賦值是ES7的寫法,ES6並不支援,需要安裝npm install --save-dev babel-preset-stage-2

//.babelrc
 "presets":["react","env","stage-2"]
import React, {Component} from 'react'
class Greeter extends Component{
   constructor (props) {
        super(props)
        this.state = {count: 0}
    }

    add=()=>{
        this.setState({
           count:this.state.count+1
        })
    }

    render () {
        return (
            <div>
                <button onClick={this.add}>add</button>
            </div>
        )
    }
}

3:只用es6

import React, {Component} from 'react'
class Greeter extends Component{
   constructor (props) {
        super(props)
        this.state = {count: 0}
        this.add=()=>{
          this.setState({
           count:this.state.count+1
          })
        }
    }



    render () {
        return (
            <div>
                <button onClick={this.add}>add</button>
            </div>
        )
    }
}