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

后端 未结 5 1626
花落未央
花落未央 2020-12-24 11:06
   import * as React from \"react\";
   import \"./App.css\";
   import PageTwo from \"./components/PageTwo\";

    export interface IPropsk {
        data?: Array&l         


        
相关标签:
5条回答
  • 2020-12-24 11:19

    You could also do something like

    fetchData = (val: string) => (event: any) => {
      alert(val);
    };
    

    Alternatively, you can set a type for your event, such as React.MouseEvent. You can read more about it here.

    0 讨论(0)
  • 2020-12-24 11:21

    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

    0 讨论(0)
  • 2020-12-24 11:26

    You can just set type this way and you will get no errors

    export interface IPropsk {
        data?: Array<Items>;
        fetchData?(): (value: string) => void;
    }
    
    0 讨论(0)
  • 2020-12-24 11:27

    As @basarat said above, when you have something like button.onclick = thisFunction(); you are already calling that function. You may want to just assign that function but not to call it,

    so you would write like this button.onclick = thisFunction;.

    0 讨论(0)
  • 2020-12-24 11:34

    With Functional Components, we use React.MouseEvent and it clears things up...

    const clickHandler = () => {
      return (event: React.MouseEvent) => {
        ...do stuff...
        event.preventDefault();
      }
    }
    
    0 讨论(0)
提交回复
热议问题