Cha*_*nth 26 javascript typescript reactjs
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;
Run Code Online (Sandbox Code Playgroud)
在上面的代码示例中,我尝试通过单击带有paremeter的按钮来调用方法(fetchData).但是我从下面的行中给出了一个错误
<input type="button" onClick={this.fetchData("dfd")} value="Search" />
Run Code Online (Sandbox Code Playgroud)
错误是
类型'void'不能赋值为'((event:MouseEvent)=> void)| 未定义".
bas*_*rat 43
在您的代码中,this.fetchData("dfd")您正在调用该函数.该函数返回void.void对于onClick期望功能的人来说是不可分的.
创建一个调用fetchData的新函数,例如onClick={() => this.fetchData("dfd")}.
bea*_*mes 26
使用功能组件,我们使用React.MouseEvent并清除了......
const clickHandler = () => {
return (event: React.MouseEvent) => {
...do stuff...
event.preventDefault();
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以做类似的事情
fetchData = (val: string) => (event: any) => {
alert(val);
};
Run Code Online (Sandbox Code Playgroud)
另外,您可以为设置类型event,例如React.MouseEvent。您可以在此处了解更多信息。
| 归档时间: |
|
| 查看次数: |
21395 次 |
| 最近记录: |