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'.
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.
Cree una nueva función que llame a fetchData, por ejemplo, onClick={() => this.fetchData("dfd")} .
Con componentes funcionales, usamos React.MouseEvent y aclara las cosas...
const clickHandler = () => { return (event: React.MouseEvent) => { ...do stuff... event.preventDefault(); } }