对两种类型的事件使用相同的事件处理程序时发生typescript错误



我有一个函数,它接受两个不同的事件对象,一个用于触摸屏,另一个用于鼠标输入。TypeScript在访问仅对其中一个事件可用的类型时显示错误。

const desktopDragHandler = (
e: React.MouseEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>
) => {
//depending on touch screen or mouse we have different properties
let position = { x: 0, y: 0 };
if (e.type === "touchmove") { //we have a touch event
let evt = typeof e.originalEvent === "undefined" ? e : e.originalEvent;
let touch = evt.touches[0] || evt.changedTouches[0];
position.x = touch.pageX;
position.y = touch.pageY;
} else { //we have a mouse event
position.x = e.clientX;
position.y = e.clientY;
}
}

ts在访问e.originalEvente.clientX or e.clientY时显示错误。如何解决这里的类型错误?

TypeScript不够聪明,无法知道e.type === "touchmove"是这两种类型之间的区别,您必须手动进行类型转换:

let evt = typeof (e as React.TouchEvent<HTMLDivElement>).originalEvent === "undefined" ? e : (e as React.TouchEvent<HTMLDivElement>).originalEvent;
position.x = (e as React.MouseEvent<HTMLDivElement>).clientX;
position.y = (e as React.MouseEvent<HTMLDivElement>).clientY;

下次请创建一个可复制的示例,我只是猜测这里发生了什么。

试试这个:

const desktopDragHandler = (
e: React.MouseEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>
) => {
//depending on touch screen or mouse we have different properties
let position = { x: 0, y: 0 };
if (e instanceof React.TouchEvent<HTMLDivElement>) { //we have a touch event
let evt = typeof e.originalEvent === "undefined" ? e : e.originalEvent;
let touch = evt.touches[0] || evt.changedTouches[0];
position.x = touch.pageX;
position.y = touch.pageY;
} else { //we have a mouse event
position.x = e.clientX;
position.y = e.clientY;
}
}

我使用这种方式。这是模态分量。处理了两个鼠标事件关闭和保存按钮点击。试试这个。

import React, { FC, MouseEventHandler } from "react";
import styles from './Modal.module.scss'
interface ModalProps {
modalTitle: String,
handleModalSaveClick?: MouseEventHandler
handleModalCancelClick?: MouseEventHandler
}
const Modal: FC<ModalProps> = ({handleModalSaveClick, modalTitle, 
handleModalCancelClick} : ModalProps) => {
return (
<div className="modal fade show" id="exampleModalLong" role="dialog" aria- 
labelledby="modal" aria-hidden="true" style={{ display: "block", paddingRight: 
"17px", opacity: 1 }}>
<div className="modal-dialog modal-dialog-centered" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="modal">{modalTitle}</h5>
<button type="button" className="close" data-dismiss="modal" aria- 
label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div className="modal-body">

</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data- 
dismiss="modal" onClick={handleModalCancelClick}>Close</button>
<button type="button" className="btn btn-primary" onClick= 
{handleModalSaveClick}>Save changes</button>
</div>
</div>
</div>
</div>
)
}
export default Modal

相关内容

最新更新