React中事件的类型定义方式

React事件的类型定义

基本的事件类型

React 搞了一套自己的事件类型,所以你没办法使用 TypeScript 内置提供的 MouseEvent 等等。在需要定义事件类型的时候,需要从 React 中导入:

import React, { Component, MouseEvent } from 'react';

export class Button extends Component {
  handleClick(event: MouseEvent) {
    event.preventDefault();
    alert(event.currentTarget.tagName); // alerts BUTTON
  }
  
  render() {
    return (
    <button onClick={this.handleClick}>
      {this.props.children}
    </button>
    );
  }
}

React 提供的事件类型有:

  • AnimationEvent 
  • ChangeEvent 
  • ClipboardEvent 
  • CompositionEvent 
  • DragEvent 
  • FocusEvent 
  • FormEvent 
  • KeyboardEvent 
  • MouseEvent 
  • PointerEvent 
  • TouchEvent 
  • TransitionEvent 
  • WheelEvent

还有一个 SyntheticEvent,用于其他所有的事件。

限制性的事件类型

如果需要限制事件类型,可以利用事件类型的泛型:

import React, { Component, MouseEvent } from 'react';

export class Button extends Component {
  /*
   * 这里我们将 handleClick 限制只能是在 HTMLButton 元素上
   */
  handleClick(event: MouseEvent<HTMLButtonElement>) {
    event.preventDefault();
    alert(event.currentTarget.tagName); // alerts BUTTON
  }

  /* 
   * 支持联合类型
   */
  handleAnotherClick(event: MouseEvent<HTMLButtonElement | HTMLAnchorElement>) {
    event.preventDefault();
    alert('Yeah!');
  }

  render() {
    return <button onClick={this.handleClick}>
      {this.props.children}
    </button>
  }
}

这里的限定的类型是 TypeScript 提供的 DOM 元素类型。

React四种定义事件方式

事件本身处的位置是一个属性 如果属性的值是一个函数

使用{}包裹,一定要保证该函数内的this指向

import React, { Component } from 'react';
export default class App extends Component {
 constructor(props) {
 super(props);
 this.add1000Fn = this.add1000.bind(this)
 }
 state = {
 count:1
 }
 add10 = () => {
 this.setState({count:this.state.count + 10})
 }
 add100 = function() { // 一般写为 add100 () {} 二者是等价的
 console.log(this);
 this.setState({count:this.state.count + 100})
 }
 add1000() {
 this.setState({count:this.state.count + 1000})
 }
 render() {
 return (
 <>
 <div>count:{ this.state.count}</div>
 {/* 1.事件定义方式1:直接在render里写行内的箭头函数 */}
 <button onClick={ ()=>{
 //如果该函数使用声明式 function(){} 内部的this指向为undefined
 this.setState({count:++this.state.count})
 }}>加一</button>
 
 {/* 2.事件定义方式2:在组件内使用箭头函数定义的一个方法 */}
 <button onClick={this.add10}>加十</button>
 
 {/* 3.事件定义方式3:直接在组件内定义一个非箭头函数的方法,然后在render里直接使用`onClick={this.handleClick.bind(this)}` */}
 <button onClick={ this.add100.bind(this)}>加一百</button>
 
 {/* 4.事件定义方式4: 直接在组件内定义一个非箭头函数的方法,然后在constructor里bind(this)*/}
 <button onClick = { this.add1000Fn }>加1000</button>
 </>
 );
 }
}

总结

作者:Pandy : )原文地址:https://blog.csdn.net/YopenLang/article/details/125910670

%s 个评论

要回复文章请先登录注册