【问题标题】:Type 'MouseEvent<Element, MouseEvent>' is not assignable to type 'MouseEvent<HTMLDivElement, MouseEvent>'类型 'MouseEvent<Element, MouseEvent>' 不可分配给类型 'MouseEvent<HTMLDivElement, MouseEvent>'
【发布时间】:2020-03-01 00:51:06
【问题描述】:

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

这是我的界面

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 类型,对吧?

【问题讨论】:

  • 我对打字稿也不太了解,但在我看来,onclick 和 onContext 上的参数都应该是事件对象。你有一些 (rowParam: number, colParam: number) 参数

标签: reactjs typescript


【解决方案1】:

解决方案

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

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

说明

层级关系如下:

⌞元素
⌞HTML元素
⌞HTMLDiv元素

错误消息显示如下:

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

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

【讨论】:

    猜你喜欢
    • 2020-04-26
    • 2019-06-29
    • 1970-01-01
    • 2020-08-16
    • 2020-11-30
    • 2017-05-06
    • 2019-01-29
    • 1970-01-01
    • 2014-11-14
    相关资源
    最近更新 更多