App下載

React事件監(jiān)聽有哪些方法?事件監(jiān)聽的三種寫法代碼分享!

猿友 2021-06-18 14:14:08 瀏覽數(shù) (5022)
反饋

在react框架的學習中我們會碰到很多不同問題,那么今天我們就來說說有關于:“React事件監(jiān)聽有哪些方法?”這個問題,小編為大家提供了一些相關信息資料,希望對大家的學習有所幫助!


方法一:在?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}>觸發(fā)</button>
        {result}
      </div>
    );
  }
}
 

方法二:通過箭頭函數(shù)改變?this?指向,代碼如下:

import React, { Component } from 'react';
export default class Group extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: true,
      title: '大西瓜'
    };
  }
  // 第二種,通過箭頭函數(shù)改變this指向
  showFunc = () => {
    this.setState({
      show: false
    });
  };
  render() {
    let result = this.state.show ? this.state.title : null;
    return (
      <div>
        <button onClick={this.showFunc}>觸發(fā)</button>
        {result}
      </div>
    );
  }
}

方法三:直接使用箭頭函數(shù)改變?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()}>觸發(fā)</button>
        {result}
      </div>
    );
  }
}

總結:

關于“React事件監(jiān)聽有哪些方法?”這個問題,小編給大家?guī)淼拇a和方法希望對大家有所幫助,這就是今天小編分享的內容,當然如果你有更好的方法或者方案也可以一起提出來和大家分享,更多有關于React的相關內容我們都可以在 React教程中進行學習和了解。


0 人點贊