类型'void'不能分配给'((event:MouseEvent <HTMLInputElement>)=> void)| 未定义"

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")}.

更多

这是TypeScript阻止的一个非常常见的错误

  • 你得到的错误不是因为TypeScript而是因为TsLint.你可以调整Linter或改变你的方法. (2认同)
  • 在渲染中使用 =&gt; 是不是很糟糕? (2认同)

bea*_*mes 26

使用功能组件,我们使用React.MouseEvent并清除了......

const clickHandler = () => {
  return (event: React.MouseEvent) => {
    ...do stuff...
    event.preventDefault();
  }
}
Run Code Online (Sandbox Code Playgroud)


Jaz*_*tha 8

您也可以做类似的事情

fetchData = (val: string) => (event: any) => {
  alert(val);
};
Run Code Online (Sandbox Code Playgroud)

另外,您可以为设置类型event,例如React.MouseEvent。您可以在此处了解更多信息。