我正在用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类型,对吗?
2条答案
按热度按时间pjngdqdw1#
解决方案
从HTMLDivElement更改为Element解决您的问题。
说明
层次关系如下:
元素
HTMLElement
简体中文
错误消息显示如下内容:
类型“Element”缺少类型“HTMLDivElement”中的以下属性:align,accessKey,accessKeyLabel,autocapitalize,还有111个。TS2322
这说明有一些属于
Element
的 prop 在HTMLDivElement
中找不到。yb3bgrhw2#
所以对于那些
Type 'MouseEvent' is not generic.
确保从
React
导入import { MouseEvent } from 'react';
或
React.MouseEvent<HTMLButtonElement>