我试图在元素上发送单击事件,但是TypeScript不喜欢any并发出警告,所以我尝试使用React.MouseEvent<HTMLElement>,但是它会抛出一个错误。
`Property 'id' does not exist on type 'EventTarget'.`const closeWindow = (e: React.MouseEvent<HTMLElement>) => {
if (e.target.id === 'modal-window') ...
}
return (
<div id='modal-window' onClick={closeWindow}>
<div id='modal-content'>...</div>
</div>
)发布于 2021-03-09 14:24:27
问题是,e.target可能是任何东西,因为它是事件的最内部目标,而不一定是设置事件处理程序的元素。
连接事件的元素是currentTarget,它正确工作:
const closeWindow = (e: React.MouseEvent<HTMLElement>) => {
if (e.currentTarget.id === 'modal-window') {
console.log("Match");
}
};(或者您可以使用HTMLDivElement进行更具体的操作。)
原因是如果单击此处的span:
<div onClick={handler}>
<span>Click me</span>
</div>e.target将是span,而不是div。e.currentTarget是div。
您已经说需要使用e.target,因为您使用它来确定单击是在modal-window上还是在modal-content上。尽管您可以使用类型断言(它们都是div元素),但是如果您要区分它们,那么可能有两个处理程序,每个处理程序一个:
return (
<div id='modal-window' onClick={closeModalWindow}>
<div id='modal-content' onClick={closeModalContent}>...</div>
</div>
);然后您将不需要id值(除非您将它们用于其他方面),并且组件将是可重用的。
例如,如果您希望modal-content上的单击不触发处理程序:
return (
<div onClick={closeWindow}>
<div onClick={e => e.stopPropagation()}>...</div>
</div>
);...then closeWindow不需要使用if。
https://stackoverflow.com/questions/66548596
复制相似问题