Type definition of React event
Basic event types
React has created its own set of event types, so you can't use the MouseEvent built-in provided by TypeScript, etc. When you need to define event types, you need to import from React:
import React, { Component, MouseEvent } from 'react'; export class Button extends Component { handleClick(event: MouseEvent) { (); alert(); // alerts BUTTON } render() { return ( <button onClick={}> {} </button> ); } }
The event types provided by React are:
AnimationEvent
ChangeEvent
ClipboardEvent
CompositionEvent
DragEvent
FocusEvent
FormEvent
KeyboardEvent
MouseEvent
PointerEvent
TouchEvent
TransitionEvent
WheelEvent
There is also a SyntheticEvent for all other events.
Restrictive event types
If you need to restrict event types, you can take advantage of event types generics:
import React, { Component, MouseEvent } from 'react'; export class Button extends Component { /* Here we restrict handleClick only on HTMLButton elements */ handleClick(event: MouseEvent<HTMLButtonElement>) { (); alert(); // alerts BUTTON } /* * Support for union types */ handleAnotherClick(event: MouseEvent<HTMLButtonElement | HTMLAnchorElement>) { (); alert('Yeah!'); } render() { return <button onClick={}> {} </button> } }
The limited type here is the DOM element type provided by TypeScript.
React four ways to define events
The location at the event itself is a property If the value of the property is a function
Use {} package, be sure to ensure that this point in the function
import React, { Component } from 'react'; export default class App extends Component { constructor(props) { super(props); this.add1000Fn = this.(this) } state = { count:1 } add10 = () => { ({count: + 10}) } add100 = function() { // Generally written as add100 () {} The two are equivalent (this); ({count: + 100}) } add1000() { ({count: + 1000}) } render() { return ( <> <div>count:{ }</div> {/* 1. Event definition method 1: Write the arrow function in the line directly in the render */} <button onClick={ ()=>{ //If the function uses the declarative function(){}, this pointer is undefined ({count:++}) }}>Add one</button> {/* 2. Event definition method 2: A method defined by using arrow functions in the component */} <button onClick={this.add10}>Add ten</button> {/* 3. Event definition method 3: Define a non-arrow function method directly in the component, and then use `onClick={(this)}` directly in the render */} <button onClick={ this.(this)}>Add one百</button> {/* 4. Event definition method 4: Define a non-arrow function method directly in the component, and then bind(this)*/} <button onClick = { this.add1000Fn }>add1000</button> </> ); } }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.