React事件监听有哪些方法?事件监听的三种写法代码分享!

猿友 2021-06-18 14:14:08 浏览数 (4083)
反馈

在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教程中进行学习和了解。


0 人点赞