所以我有一个带有按钮的React组件,该按钮具有一个使用data- *属性的单击处理程序。如果这是直接的React,那么我知道如何从data- *属性获取值。但是,我正在学习如何使用TypeScript,所以我不知道如何访问此属性。那么使用TypeScript访问data- *属性的最佳方法是什么?
这是我的按钮的JSX代码:
<button type="button" className="NavLink" data-appMode={ AppMode.MAIN } onClick={ this.handleAppModeClick.bind(this) }>Main</button>
这是我的点击事件处理程序:
handleAppModeClick(e: React.MouseEvent<HTMLElement>) {
// What code should go here to access the data-appMode attribute?
}
您很可能将不得不使用as
语法,这取决于您要在e.target上访问哪个属性。
handleAppModeClick(e: React.MouseEvent) {
const appMode = (e.target as HTMLButtonElement).getAttribute('data-appMode');
}
在事件函数中,您具有e变量,e表示通过单击按钮触发的事件,e具有target属性,因此为了从元素中访问属性,您应该执行以下操作:
handleAppModeClick(e: React.MouseEvent<HTMLElement>) {
const target = e.target as HTMLElement;
let attr = target.getAttribute("data-attribute-name-here");
//do something
}
使用e.currentTarget,然后使用HTML标准方法getAttribute
。无需强制。
const appMode = e.currentTarget.getAttribute('data-appmode');
((请注意属性名称中的小写字母,以避免引起警告警告)
currentTarget
已经正确输入。如果您阅读the definitions of React's event types,则可以看到MouseEvent
扩展了SyntheticEvent
,扩展了BaseSyntheticEvent
,其中包括属性target
和currentTarget
等。您提供的HTMLElement
类型将应用于currentTarget
,因此您可以访问所有正确的内容。如果您使用target
,则会收到有关getAttribute
对于类型EventTarget
无效的编译错误。
currentTarget
是您要放置处理程序的元素onClick
。 target
是事件最初来自(more here)的位置。这不一定相同,因为事件冒泡了。请参阅PR referenced in the type definitions file,以获取有关为什么键入不同内容的完整讨论。