React TypeScript 从点击事件中获取数据属性 [英] React TypeScript get Data Attribute From Click Event

查看:360
本文介绍了React TypeScript 从点击事件中获取数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个带有按钮的 React 组件,它有一个使用 data-* 属性的点击处理程序.如果这是直接 React 那么我知道如何从 data-* 属性中获取值.但是我正在学习如何使用 TypeScript,所以我不知道如何访问这个属性.那么使用 TypeScript 访问 data-* 属性的最佳方法是什么?

So I have a React component with a button which has a click handler which uses the data-* attribute. If this was straight React then I know how to get the value from the data-* attribute. However I am learning how to use TypeScript so I have no idea how to get access to this attribute. So what is the best way to get access to the data-* attribute using TypeScript?

这是我的按钮的 JSX 代码:

This is my JSX code for the button:

<button type="button" className="NavLink" data-appMode={ AppMode.MAIN } onClick={ this.handleAppModeClick.bind(this) }>Main</button>

这是我的点击事件处理程序:

This is my handler for the click event:

handleAppModeClick(e: React.MouseEvent<HTMLElement>) {
    // What code should go here to access the data-appMode attribute?
}

推荐答案

使用 e.currentTarget 然后使用 HTML 标准方法 getAttribute.无需强制.

Use e.currentTarget and then use HTML standard method getAttribute. No coercion necessary.

const appMode = e.currentTarget.getAttribute('data-appmode');

(注意属性名称中的小写,以避免反应警告)

(note lowercase in the attribute name to avoid warnings from react)

如果你阅读了React 事件的定义类型可以看到MouseEvent扩展了SyntheticEvent,它扩展了BaseSyntheticEvent,其中包含了属性targetcurrentTarget 等.您提供的 HTMLElement 类型将应用于 currentTarget,因此您可以访问所有正确的内容.如果您使用 target,您将收到关于 getAttribute 对类型 EventTarget 无效的编译错误.

If you read the definitions of React's event types you can see that MouseEvent extends SyntheticEvent, which extends BaseSyntheticEvent, which includes the property target and currentTarget, among others. The HTMLElement type you provide gets applied to currentTarget, so you have access to all the right stuff. If you use target you'll get a compile error about getAttribute not being valid for type EventTarget.

currentTarget 是您放置处理程序的元素,onClick.target 是事件最初的来源(更多这里).这不一定相同,因为事件会冒泡.请参阅类型定义文件中引用的 PR 以获取有关为什么要输入类型的完整讨论不一样.

The currentTarget is the element where you're putting your handler, onClick. The target is where the event originally came from (more here). This is not necessarily the same because events bubble up. See the PR referenced in the type definitions file for a complete discussion on why they're typed differently.

这篇关于React TypeScript 从点击事件中获取数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆