react事件处理,为类方法绑定this

本文深入探讨了React事件绑定属性的命名规则、如何在JSX语法中使用函数作为事件处理函数、阻止事件默认行为的方法、以及类方法中绑定this的技巧。通过实例演示了属性初始化器语法和箭头函数的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • react事件绑定属性的命名采用驼峰命名法,
  • 如果采用JSX的语法,需要传入一个函数作为事件处理函数,而不是一个字符串(DOM元素的写法)。

阻止事件的默认行为:

  • 不能使用返回false的方式来阻止默认行为,必须明确的使用preventDefault

在类方法中绑定this

注:要谨慎的在类方法中使用this,因为类方法默认不会绑定this。需要主动的将这类方法绑定到this上。

为类方法上绑定this的方法:

  • 在构造方法中为类方法绑定this
class LoggingButton extends React.Component {
  constructor(props){
		super(props);
		
		//类方法,必须为每个类方法绑定this,否则在类方法总使用this时,会是undefined
		this.handleClick = this.handleClick.bind(this);
 }

  handleClick(){
    console.log('this is:', this);
  }
 
  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}
  • 属性初始化器语法
class LoggingButton extends React.Component {
  // 这个语法确保了 `this` 绑定在  handleClick 中
  // 这里只是一个测试
  handleClick = () => {
    console.log('this is:', this);
  }
 
  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}
  • 调函数中使用 箭头函数:
class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }
 
  render() {
    //  这个语法确保了 `this` 绑定在  handleClick 中
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值