' 不可分配给类型 'MouseEvent',reactjs,typescript"/>

首页 > 解决方案 > 输入“鼠标事件”' 不可分配给类型 'MouseEvent'

问题描述

我正在打字稿中编写一个反应应用程序,我试图同时处理右键单击和左键单击。

这是我的界面

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 |             />

我对打字稿不太了解,但根据我的说法,HTMLDivElement 应该是 HTMLElement 类型,对吧?

标签: reactjstypescript

解决方案


解决方案

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

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

解释

层次关系如下:

⌞元素 ⌞HTML元素
  ⌞HTMLDiv
    元素

错误消息显示如下:

“Element”类型缺少“HTMLDivElement”类型中的以下属性:align、accessKey、accessKeyLabel、autocapitalize 等 111 个。TS2322

这说明有一些属于 的道具Element找不到HTMLDivElement


推荐阅读