Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

javascript - Type 'void' is not assignable to type '((event: MouseEvent<HTMLInputElement>) => void) | undefined'

   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;

In the above code example I tried to call a method(fetchData ) by clicking button with a paremeter.But I gives a error from following line

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

The error is

type 'void' is not assignable to type '((event: MouseEvent) => void) | undefined'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your code this.fetchData("dfd") you are calling the function. The function returns void. void is not assingable to onClick which expects a function.

Fix

Create a new function that calls fetchData e.g. onClick={() => this.fetchData("dfd")}.

More

This is a very common error prevented by TypeScript ??


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...