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;
在上面的代码示例中,我尝试调用一个方法(获取数据)通过单击带有参数的按钮。但是我从以下行给出了错误
<input type="button" onClick={this.fetchData("dfd")} value="Search" />
错误是
类型“void”不可分配给类型“((event: MouseEvent) => void) |不明确的'。
在你的代码中this.fetchData("dfd")
你是calling功能。函数返回void
. void
不可分配给onClick
它需要一个函数。
Fix
创建一个调用 fetchData 的新函数,例如onClick={() => this.fetchData("dfd")}
.
更多信息
这是 TypeScript 避免的一个非常常见的错误 ???? https://basarat.gitbook.io/typescript/main/interpreting-errors
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)