reactjs 类型“MouseEvent〈Element,MouseEvent>”不能分配给类型“MouseEvent〈HTMLDivElement,MouseEvent>”

oxcyiej7  于 2023-04-11  发布在  React
关注(0)|答案(2)|浏览(602)

我正在用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类型,对吗?

pjngdqdw

pjngdqdw1#

解决方案

HTMLDivElement更改为Element解决您的问题。

// Before
const handleContextMenu = (...) => (e: React.MouseEvent<HTMLDivElement, MouseEvent>) : void => {
  ...
}
// After
const handleContextMenu = (...) => (e: React.MouseEvent<Element, MouseEvent>) : void => {
  ...
}

说明

层次关系如下:
元素
HTMLElement
简体中文

错误消息显示如下内容:
类型“Element”缺少类型“HTMLDivElement”中的以下属性:align,accessKey,accessKeyLabel,autocapitalize,还有111个。TS2322
这说明有一些属于Element的 prop 在HTMLDivElement中找不到。

yb3bgrhw

yb3bgrhw2#

所以对于那些
Type 'MouseEvent' is not generic.
确保从React导入
import { MouseEvent } from 'react';

React.MouseEvent<HTMLButtonElement>

相关问题