reactjs - 输入“鼠标事件”' 不可分配给类型 '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 类型,对吧?
解决方案
解决方案
从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
。
推荐阅读
- ubuntu - 如何更改 Ubuntu 18.04 gdm3 中的默认会话?
- swift - 在分配仍然存在的情况下重置区域分配器
- sqlalchemy - 通过项目管道提交数据库的最佳方式?
- java - 通过 JDBC 访问 Cloudera Hive 时如何将执行引擎设置为 spark
- java - 旋转僵尸面对玩家
- svg - Inkscape 忽略
- css - .Header h1 与 margin-top 和 margin-bottom 一起消失
- javascript - 这是如何工作的“elements.map(({ length :lengthFooBArX }) => lengthFooBArX);”
- xml - 将外部数据导入 Firebase 的最佳方式是什么?
- javascript - 如何限制用户在可编辑字段中添加图像