1. 程式人生 > 程式設計 >React中事件繫結this指向三種方法的實現

React中事件繫結this指向三種方法的實現

1.箭頭函式

1.利用箭頭函式自身不繫結this的特點;

2.render()方法中的this為元件例項,可以獲取到setState();

class App extends React.Component{
    state ={
        count: 0
    }
    // 事件處理程式
    onIncrement() {
        console.log('事件處理函式程式設計客棧中的this:',this)
        this.setState({
            count:this.state.count+1
        })
    }
    // 渲染
    render() {
        return (
            <div>
                <h1> {this.state.count}</h1>
              // 箭頭函式中的this指向外部環境,此處為:render()方法
                <button onClick={()=>this.onIncrement()}>+1</button>
                {/* <button onClick={this.onIncrement()}>+1</button> */}
            </div>
        )
    }
}

2.Function.proptype.bind()

1.利用ES5中的bind方法,將事件處理程式中的this與元件例項繫結到一起

class App extends React.Component{
    constructor() {
        super()
        // 資料
        this.state ={
            count: 0
        }
        // 第一中方法.bind 改變this指向,返回一個函式,不執行該函式
        this.onIncrement = this.onIncrement程式設計客棧.bind(this)
    }
     // 事件處理程式
     onIncrement() {
         console.log('事件處理函式中的this:',this)
         this.setState({
             count:this.state.count+1
         })
     }
    // 渲染
    render() {
        return (
            <div>
                <h1> {this.state.count}</h1>
                <button onClick={this.onIncrement}>+1</button>
                {/* <button onClick={this.onIncrement()}>+1</button> */}
            </div>
        )
    }
}

3.class的例項方法

1.利用箭頭函式形式的class例項方法

2.該語法是實驗性語法,但是由於babel的存在就可以直接使用

class App extends React.Component{
    constructor() {
        super()
        // 資料
        this.state ={
            count: 0
        }
    }
 程式設計客棧     // 事件處理程式 
      onIncrement=()=> {
        console.log('事件處理函式中的this:',this)
        this.setState({
            count:this.state.http://www.cppcns.com
count+1 }) } // 渲染 render() { return ( <div> <h1> {this.state.count}</h1> <button onClick={this.onIncrement}>+1</button> http://www.cppcns.com {/* <button onClick={this.onIncrement()}>+1</button> */} </div> ) } }

到此這篇關於React中事件繫結this指向三種方法的實現的文章就介紹到這了,更多相關React 事件繫結this指向內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!