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

292
Views
El tipo 'void' no se puede asignar al tipo '((event: MouseEvent<HTMLInputElement>) => void) | indefinido'
 import * as React from "react"; import "./App.css"; import PageTwo from "./components/PageTwo"; export interface IPropsk { data?: Array<Items>; fetchData?(value: string): void; } export interface IState { isLoaded: boolean; hits: Array<Items>; value: string; } class App extends React.Component<IPropsk, IState> { constructor(props: IPropsk) { super(props); this.state = { isLoaded: false, hits: [], value: "" this.handleChange = this.handleChange.bind(this); } fetchData = val => { alert(val); }; handleChange(event) { this.setState({ value: event.target.value }); } render() { return ( <div> <div> <input type="text" value={this.state.value} onChange= {this.handleChange} <input type="button" onClick={this.fetchData("dfd")} value="Search" /> </div> </div> ); } } export default App;

En el ejemplo de código anterior, traté de llamar a un método ( fetchData ) haciendo clic en el botón con un parámetro. Pero me da un error al seguir la línea

 <input type="button" onClick={this.fetchData("dfd")} value="Search" />

el error es

el tipo 'void' no se puede asignar al tipo '((event: MouseEvent) => void) | indefinido'.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

En su código this.fetchData("dfd") está llamando a la función. La función devuelve void . void no se puede asignar a onClick que espera una función.

Arreglar

Cree una nueva función que llame a fetchData, por ejemplo, onClick={() => this.fetchData("dfd")} .

Más

Este es un error muy común prevenido por TypeScript 🌹

over 4 years ago · Santiago Trujillo Report

0

Con componentes funcionales, usamos React.MouseEvent y aclara las cosas...

 const clickHandler = () => { return (event: React.MouseEvent) => { ...do stuff... event.preventDefault(); } }
over 4 years ago · Santiago Trujillo Report

0

También podrías hacer algo como

 fetchData = (val: string) => (event: any) => { alert(val); };

Alternativamente, puede establecer un tipo para su event , como React.MouseEvent . Puedes leer más sobre esto aquí .

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!