美文网首页
【三】React事件监听三种写法

【三】React事件监听三种写法

作者: 编程小橙子 | 来源:发表于2020-02-09 01:32 被阅读0次
image.png

方式一:在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事件监听三种写法

      本文链接:https://www.haomeiwen.com/subject/lhtgxhtx.html