我目前正在使用 ant design 开发我的 React 和 TypeScript 项目。
我有按钮组件,我想在单击按钮时获取按钮的值和内部文本。
所以这是我的代码 on codesandbox
import { Button, message } from "antd";
import { MouseEvent } from "react";
function App() {
const buttonClickEvent = (e: MouseEvent<HTMLButtonElement>) => {
message.info(e.currentTarget.value);
message.info(e.currentTarget.innerText);
};
return (
<>
<Button onClick={buttonClickEvent} value="antd">
antd button
</Button>
<br />
<button type="button" onClick={buttonClickEvent} value="HTML">
HTML button
</button>
</>
);
}
export default App;
看起来工作正常,但出现类型错误。 这是错误消息。
Type '(e: MouseEvent<HTMLButtonElement>) => void' is not assignable to type 'MouseEventHandler<HTMLAnchorElement> & MouseEventHandler<HTMLButtonElement>'.
Type '(e: MouseEvent<HTMLButtonElement>) => void' is not assignable to type 'MouseEventHandler<HTMLAnchorElement>'.
Types of parameters 'e' and 'event' are incompatible.
Type 'MouseEvent<HTMLAnchorElement, MouseEvent>' is not assignable to type 'MouseEvent<HTMLButtonElement, MouseEvent>'.
Type 'HTMLAnchorElement' is missing the following properties from type 'HTMLButtonElement': disabled, form, formAction, formEnctype, and 11 more.typescript(2322)
button.d.ts(27, 5): The expected type comes from property 'onClick' which is declared here on type 'IntrinsicAttributes & Partial<{ href: string; target?: string | undefined; onClick?: MouseEventHandler<HTMLAnchorElement> | undefined; } & BaseButtonProps & Omit<...> & { ...; } & Omit<...>> & RefAttributes<...>'
我不想在按钮单击事件上使用
any
类型。
使用 ant design 按钮组件获取事件目标值的正确方法是什么?
你的函数返回 void。 void 不能分配给需要函数的 onClick。
创建一个调用 fetchData 的新函数,例如onClick={(e) => buttonClickEvent(e)}。这解决了这个错误。 链接
之后的代码会给你另一个错误。在 e.currentTarget.value。 解决 put (e.currentTarget as HTMLButtonElement).value.