简体   繁体   中英

how to solve the onClick problem in typescript Reactjs

my function is like this:

async function handleFavorites(event: MouseEvent) {
 event.preventDefault();
}

on my button, I'm using onclick to call this function but it's not working

<button
 type="submit"
 value={favorites}
 onChange={e => setFavorites(e.currentTarget.value)}
 onClick={() => { 
   handleFavorites();
 }}
>

Error: Expected 1 arguments, but got 0. An argument for 'event' was not provided.

does anyone know how to solve? or have any tips?

The problem is that you are not passing the event argument to your handler. This should work:

<button
 type="submit"
 value={favorites}
 onChange={e => setFavorites(e.currentTarget.value)}
 onClick={handleFavorites}
>

You don't need to write functions to onclick again. Try it this way.

 function handleFavorites(e) { e.preventDefault(); } onClick={handleFavorites}

onClick={(e) => { handleFavorites(e); }}

Or

onClick={handleFavorites}

React has its own "synthetic events" which wrap the underlying native DOM events. The core of your problem is the confusion between the synthetic event and the native event. Your handleFavorites method is currently expecting a native event, while the button onClick provides a synthetic event. With your current types, you could actually do this onClick={e => handleFavorites(e.nativeEvent)} , though I don't recommend it.

Everyone else is correct that you want to pass your callback as onClick={handleFavorites} . But in order to do that, your handleFavorites needs to accept a synthetic event. React and the DOM both have their own interfaces for a MouseEvent with the same name, so you need to make sure that you are using the right one.

  1. You can change the type to (event: React.MouseEvent) which makes it clear that this is react synthetic event.
  2. You can keep (event: MouseEvent) and import the react version into your file import React, {MouseEvent} from "react";

Note that the native event and the synthetic event both have a preventDefault() method, so switching the type won't necessitate changes in the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM