1. 程式人生 > 其它 >從JSX中抽離事件處理程式

從JSX中抽離事件處理程式

將邏輯抽離到單獨的方法中,保證JSX結構清晰

事件繫結this指向

1.箭頭函式

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

//1. 匯入react
import React from 'react';
import ReactDOM from 'react-dom';

/*
  從JSX中抽離事件處理程式
*/

class App extends React.Component {
  state = {
    count: 0,
    test: 'a'
  }

  //事件處理程式
  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> ) } } //渲染元件 ReactDOM.render(<App />, document.getElementById('root'))

2.Function.prototype.bind()

//1. 匯入react
import React from 'react';
import ReactDOM from 'react-dom';

/*
  從JSX中抽離事件處理程式
*/

class App extends React.Component {
  

  constructor() {
    super()

    
this.state = { count: 0 } 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> </div> ) } } //渲染元件 ReactDOM.render(<App />, document.getElementById('root'))

3.class的例項方法

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

//1. 匯入react
import React from 'react';
import ReactDOM from 'react-dom';

/*
  從JSX中抽離事件處理程式
*/

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>
        <button onClick={this.onIncrement}>+1</button>
      </div>
    )
  }
}

//渲染元件
ReactDOM.render(<App />, document.getElementById('root'))