App下載

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

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

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


方法一:在?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);
  }
  // 調(diào)用該方法
  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: '大西瓜'
    };
  }
  // 調(diào)用該方法
  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>
    );
  }
}

總結(jié):

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


0 人點(diǎn)贊