gpt4 book ai didi

reactjs - 'MouseEvent' 类型不可分配给 'MouseEvent' 类型

转载 作者:行者123 更新时间:2023-12-03 23:08:42 29 4
gpt4 key购买 nike

我正在用 typescript 编写一个 react 应用程序,我试图同时处理右键单击和左键单击。

这是我的界面

interface ButtonProps {
value: CellValue;
state: CellState;
row: number;
col: number;
onClick(rowParam: number, colParam: number) : (e: React.MouseEvent) => void;
onContext(rowParam: number, colParam: number) : (e: React.MouseEvent) => void;
}

现在我已经声明了回调函数
const handleContextMenu = (rowParam: number, cellParam: number) => (e: React.MouseEvent<HTMLDivElement, MouseEvent>) : void => {
e.preventDefault();
}

最后声明了我的组件
<Button 
key={`${rowIndex}*${cellIndex}`}
value={cell.value}
state={cell.state}
onClick={handleCellClick}
onContext={handleContextMenu}
row={rowIndex}
col={cellIndex}
/>

但我收到一个错误
Type '(rowParam: number, cellParam: number) => (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void' is not assignable to type '(rowParam: number, colParam: number) => (e: MouseEvent<Element, MouseEvent>) => void'.
Type '(e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void' is not assignable to type '(e: MouseEvent<Element, MouseEvent>) => void'.
Types of parameters 'e' and 'e' are incompatible.
Type 'MouseEvent<Element, MouseEvent>' is not assignable to type 'MouseEvent<HTMLDivElement, MouseEvent>'.
Type 'Element' is missing the following properties from type 'HTMLDivElement': align, accessKey, accessKeyLabel, autocapitalize, and 111 more. TS2322

53 | state={cell.state}
54 | onClick={handleCellClick}
> 55 | onContext={handleContextMenu}
| ^
56 | row={rowIndex}
57 | col={cellIndex}
58 | />

我不太了解 typescript ,但据我说 HTMLDivElement 应该是 HTMLElement 类型,对吗?

最佳答案

解决方案
HTMLDivElement 更改为 元素 解决您的问题。

// Before
const handleContextMenu = (...) => (e: React.MouseEvent<HTMLDivElement, MouseEvent>) : void => {
...
}
// After
const handleContextMenu = (...) => (e: React.MouseEvent<Element, MouseEvent>) : void => {
...
}
解释
层级关系如下:
⌞元素
⌞HTML元素
⌞HTMLDiv元素
  • 引用:Interface HTMLDivElement

  • 错误消息显示如下:

    Type 'Element' is missing the following properties from type 'HTMLDivElement': align, accessKey, accessKeyLabel, autocapitalize, and 111 more. TS2322


    这说明在 Element 中找不到一些属于 HTMLDivElement 的 Prop 。

    关于reactjs - 'MouseEvent<Element, MouseEvent>' 类型不可分配给 'MouseEvent<HTMLDivElement, MouseEvent>' 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60471034/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com