Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

294
Views
Texto mecanografiado: tipos de eventos React

¿Cuál es el tipo correcto para los eventos React? Inicialmente solo usé any por simplicidad. Ahora, estoy tratando de limpiar las cosas y evitar el uso de any por completo.

Entonces, en una forma simple como esta:

 export interface LoginProps { login: { [k: string]: string | Function uname: string passw: string logIn: Function } } @inject('login') @observer export class Login extends Component<LoginProps, {}> { update = (e: React.SyntheticEvent<EventTarget>): void => { this.props.login[e.target.name] = e.target.value } submit = (e: any): void => { this.props.login.logIn() e.preventDefault() } render() { const { uname, passw } = this.props.login return ( <div id='login' > <form> <input placeholder='Username' type="text" name='uname' value={uname} onChange={this.update} /> <input placeholder='Password' type="password" name='passw' value={passw} onChange={this.update} /> <button type="submit" onClick={this.submit} > Submit </button> </form> </div> ) } }

¿Qué tipo utilizo aquí como tipo de evento?

React.SyntheticEvent<EventTarget> no parece estar funcionando ya que recibo un error que indica que el name y el value no existen en el target .

Se agradecería mucho una respuesta más generalizada para todos los eventos.

Gracias

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

La interfaz SyntheticEvent es genérica:

 interface SyntheticEvent<T> { ... currentTarget: EventTarget & T; ... }

(Técnicamente, la propiedad currentTarget está en el tipo BaseSyntheticEvent principal).

Y currentTarget es una intersección de la restricción genérica y EventTarget .
Además, dado que sus eventos son causados por un elemento de entrada, debe usar ChangeEvent ( en el archivo de definición , los documentos de reacción ).

Debiera ser:

 update = (e: React.ChangeEvent<HTMLInputElement>): void => { this.props.login[e.currentTarget.name] = e.currentTarget.value }

(Nota: esta respuesta sugirió originalmente usar React.FormEvent . La discusión en los comentarios está relacionada con esta sugerencia, pero React.ChangeEvent debe usarse como se muestra arriba).

over 4 years ago · Santiago Trujillo Report

0

El problema no es con el tipo de evento, sino que la interfaz EventTarget en TypeScript solo tiene 3 métodos:

 interface EventTarget { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; dispatchEvent(evt: Event): boolean; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } interface SyntheticEvent { bubbles: boolean; cancelable: boolean; currentTarget: EventTarget; defaultPrevented: boolean; eventPhase: number; isTrusted: boolean; nativeEvent: Event; preventDefault(): void; stopPropagation(): void; target: EventTarget; timeStamp: Date; type: string; }

Por lo tanto, es correcto que el name y el value no existan en EventTarget. Lo que debe hacer es convertir el objetivo en el tipo de elemento específico con las propiedades que necesita. En este caso será HTMLInputElement .

 update = (e: React.SyntheticEvent): void => { let target = e.target as HTMLInputElement; this.props.login[target.name] = target.value; }

También para eventos en lugar de React.SyntheticEvent, también puede escribirlos de la siguiente manera: Event , MouseEvent , KeyboardEvent ...etc, depende del caso de uso del controlador.

La mejor manera de ver todas estas definiciones de tipos es verificar los archivos .d.ts tanto de TypeScript como de React.

Consulte también el siguiente enlace para obtener más explicaciones: ¿Por qué Event.target no es un elemento en TypeScript?

over 4 years ago · Santiago Trujillo Report

0

Para combinar las respuestas de Nitzan y Edwin, descubrí que algo como esto funciona para mí:

 update = (e: React.FormEvent<EventTarget>): void => { let target = e.target as HTMLInputElement; this.props.login[target.name] = target.value; }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!