reactjs - 由于 React Typescript 中的类型错误,将事件作为 typescript 中的参数传递失败
问题描述
我正在尝试将此事件传递给我的类型脚本文件中的事件侦听器,但是事件侦听器不允许传递任何其他事件类型,除了 Event、MouseEvent 和其他一些类型。
public componentDidMount() {
const app = document.querySelector(".app");
app.addEventListener("click", ((event: React.SyntheticEvent<HTMLElement>) => {
this._handleWhiteSpaceEvent(event);
}) as EventListener);
}
事件侦听器不断抛出错误
Conversion of type '(event: React.SyntheticEvent<HTMLElement>) => void' to type 'EventListener' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Types of parameters 'event' and 'evt' are incompatible
或者当我尝试 React.MouseEvent
Conversion of type '(event: React.MouseEvent<HTMLElement>) => void' to type 'EventListener' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Types of parameters 'event' and 'evt' are incompatible.
有人能帮忙吗?
解决方案
当您直接在元素上设置事件侦听器时app
,您获得的事件不是React.SyntheticEvent
. 这只是定义中的MouseEvent
常规lib.dom.ts
。onClick
在 DOM 节点上设置属性时,您会收到一个合成事件。
您需要确保您有一个有效的app
元素,而不是null
因为document.querySelector
不能保证找到结果。
Event
您可以通过可选链接获得公正。
app?.addEventListener("click", (event: Event) => {
this._handleWhiteSpaceEvent(event);
});
为了使用该MouseEvent
类型,您必须细化app
fromElement
到的类型HTMLElement
。
if (app instanceof HTMLElement) {
app.addEventListener("click", (event: MouseEvent) => {
this._handleWhiteSpaceEvent(event);
});
}
这些类型都不像 React 事件类型那样通用。通过 JSX 设置事件侦听器,您可以通过更少的检查获得更多信息。
推荐阅读
- amp-html - 在 google-amp 中的页面加载时运行脚本并验证为 amp-page
- redis - 如何在 REDIS 中标记一个键,以便稍后我可以删除与该标记匹配的所有键?
- javascript - 我的代码不刷新就无法工作。它没有显示正确的页面颜色
- swift - 更改 IBOutlet 标题时意外发现 nil
- javascript - 如何将两个 html 表单与一个谷歌表格链接?
- amazon-web-services - 未找到字段的值 - AppSync AWS
- python - 查找数据框中的最低时间值
- java - JAVA Hibernate 合并正在更新而不是合并
- python - 使用 python 在现有 SQL Server 表中附加来自 excel 的数据
- flutter - 哪些 Flutter 默认插件很重要?