[英]how to solve the onClick problem in typescript Reactjs
my function is like this:我的 function 是这样的:
async function handleFavorites(event: MouseEvent) {
event.preventDefault();
}
on my button, I'm using onclick to call this function but it's not working在我的按钮上,我使用 onclick 来调用这个 function 但它不起作用
<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.错误:预期为 1 arguments,但得到 0。未提供“事件”的参数。
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.您无需再次向 onclick 写入函数。 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. React 有自己的“合成事件” ,它封装了底层的原生 DOM 事件。 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.您的
handleFavorites
方法当前需要一个本机事件,而button
onClick
提供一个合成事件。 With your current types, you could actually do this onClick={e => handleFavorites(e.nativeEvent)}
, though I don't recommend it.使用您当前的类型,您实际上可以这样做
onClick={e => handleFavorites(e.nativeEvent)}
,尽管我不推荐它。
Everyone else is correct that you want to pass your callback as onClick={handleFavorites}
.您希望将回调传递为
onClick={handleFavorites}
的其他人都是正确的。 But in order to do that, your handleFavorites
needs to accept a synthetic event.但为了做到这一点,您的
handleFavorites
需要接受一个合成事件。 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. React 和 DOM 都有自己的同名
MouseEvent
接口,因此您需要确保使用正确的接口。
(event: React.MouseEvent)
which makes it clear that this is react synthetic event.(event: React.MouseEvent)
,这清楚地表明这是反应合成事件。(event: MouseEvent)
and import the react version into your file import React, {MouseEvent} from "react";
(event: MouseEvent)
并将反应版本导入您的文件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.请注意,本机事件和合成事件都具有
preventDefault()
方法,因此切换类型不需要更改 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.