react状态(class)组件绑定事件的四种方式

在使用react类组件中绑定事件有以下四种方式(若有需要,推荐使用第一种方式):

import React, { Component } from "react";
class Cat extends Component {
  constructor() {
    super();
    // 第四种对应处理
    this.catSayd = this.catSayd.bind(this);
  }

  // 第一种
  catSaya = () => {
    alert("hello cat a");
  };
  // 第二种
  catSayb() {
    alert("hello cat b");
  }
  // 第三种
  catSayc() {
    alert("hello cat c");
  }
  // 第四种
  catSayd() {
    alert("hello cat d");
  }

  render() {
    return (
      <>
        <button onClick={this.catSaya}>Cat say a</button>
        <button onClick={this.catSayb.bind(this)}>Cat say b</button>
        <button onClick={() => this.catSayc()}>Cat say c</button>
        <button onClick={this.catSayd}>Cat say d</button>
      </>
    );
  }
}
export default Cat;

从上面四种事件绑定方式可以看出,类组件与函数组件很大的不同之处在于有个this,所以在类组件中你要时时刻刻注意this指向的问题而在函数组件中就不需要考虑。

而且类组件与函数组件还有一个区别就是:类组件有可以有状态(sate)所以也被称为状态组件而函数组件没有。但在react 16.8 hooks出来之后,官方力推使用react hooks实现状态组件,摒弃类组件的使用。利用react hooks中用useState管理状态,useEffect替换类组件中生命周期钩子函数,从而替代类组件的使用随之也解决了其中this指向问题的这一痛点,在hooks的加持下也使得react代码变得更加简单易懂。

import React, { useState, useEffect } from "react";

function Cat() {
  const [count, setCount] = useState(0);
  function catSay() {
    alert(`hello cat count=${count}`);
  }
  useEffect(() => {
    console.log(count);
  },[count]);
  
  return (
    <>
      <button onClick={()=>{setCount(count+1)}}>count++ = {count}</button>
      <button onClick={catSay}>cat catSay</button>
    </>
  );
}
export default Cat;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值