TypeScript发送事件类型以获取target.id

Álv*_*aro 1 typescript reactjs

我正在尝试发送元素上的单击事件,但 TypeScript 不喜欢any并发出警告,因此我正在尝试,React.MouseEvent<HTMLElement>但随后它抛出了错误。

`Property 'id' does not exist on type 'EventTarget'.`
Run Code Online (Sandbox Code Playgroud)
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>
)
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

问题是它e.target可能是任何东西,因为它是事件最里面的目标,不一定是您设置事件处理程序的元素。

您挂钩事件的元素是currentTarget,它工作正常:

const closeWindow = (e: React.MouseEvent<HTMLElement>) => { 
    if (e.currentTarget.id === 'modal-window') {
        console.log("Match");
    }
};
Run Code Online (Sandbox Code Playgroud)

(或者你可以HTMLDivElement更具体一些。)

原因是,如果您单击此处span

<div onClick={handler}>
    <span>Click me</span>
</div>
Run Code Online (Sandbox Code Playgroud)

e.target将是span,而不是dive.currentTarget是个div


您说过您需要使用,e.target因为您使用它来确定点击是否为modal-windowmodal-content。尽管您可以使用类型断言(它们都是div元素),但如果您无论如何都要区分它们,则可能有两个处理程序,每个处理程序一个:

return (
    <div id='modal-window' onClick={closeModalWindow}>
        <div id='modal-content' onClick={closeModalContent}>...</div>
    </div>
);
Run Code Online (Sandbox Code Playgroud)

那么您就不需要这些id值(除非您将它们用于其他用途)并且该组件将是可重用的。

如果您希望点击modal-content不触发您的处理程序,例如:

const closeWindow = (e: React.MouseEvent<HTMLElement>) => { 
    if (e.currentTarget.id === 'modal-window') {
        console.log("Match");
    }
};
Run Code Online (Sandbox Code Playgroud)

...然后closeWindow不需要使用if.