在react框架的学习中我们会碰到很多不同问题,那么今天我们就来说说有关于:“React事件监听有哪些方法?”这个问题,小编为大家提供了一些相关信息资料,希望对大家的学习有所帮助!

方法一:在​constructor​中使用​bind​绑定,改变​this​的指向,代码如下:

import React, { Component } from 'react';
export default class Group extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: true,
      title: '大西瓜'
    };
    // 写法一:事件绑定改变this指向
    this.showFunc = this.showFunc.bind(this);
  }
  // 调用该方法
  showFunc() {
    this.setState({
      show: false
    });
  }
  render() {
    let result = this.state.show ? this.state.title : null;
    return (
      <div>
        <button onClick={this.showFunc}>触发</button>
        {result}
      </div>
    );
  }
}
 

方法二:通过箭头函数改变​this​指向,代码如下:

import React, { Component } from 'react';
export default class Group extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: true,
      title: '大西瓜'
    };
  }
  // 第二种,通过箭头函数改变this指向
  showFunc = () => {
    this.setState({
      show: false
    });
  };
  render() {
    let result = this.state.show ? this.state.title : null;
    return (
      <div>
        <button onClick={this.showFunc}>触发</button>
        {result}
      </div>
    );
  }
}

方法三:直接使用箭头函数改变​this​的指向,代码如下:

import React, { Component } from 'react';
export default class Group extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: true,
      title: '大西瓜'
    };
  }
  // 调用该方法
  showFunc() {
    this.setState({
      show: false
    });
  }
  render() {
    let result = this.state.show ? this.state.title : null;
    return (
      <div>
        <button onClick={() => this.showFunc()}>触发</button>
        {result}
      </div>
    );
  }
}

总结:

关于“React事件监听有哪些方法?”这个问题,小编给大家带来的代码和方法希望对大家有所帮助,这就是今天小编分享的内容,当然如果你有更好的方法或者方案也可以一起提出来和大家分享,更多有关于React的相关内容我们都可以在 React教程中进行学习和了解。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。