从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'))

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐