React TypeScript get Data Attribute From Click Event

ぃ、小莉子 提交于 2020-12-08 06:15:41

问题


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?

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?
}

回答1:


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)

currentTarget is already correctly typed.

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.

What's the difference?

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.




回答2:


You most likely will have to use as syntax , depending which property you want to access on e.target.

handleAppModeClick(e: React.MouseEvent) {
    const appMode = (e.target as HTMLButtonElement).getAttribute('data-appMode');
}



回答3:


In your event function you have e variable, e represents an event fired by clicking the button, e has a target property so, in order to access an attribute from the element you should do:

handleAppModeClick(e: React.MouseEvent<HTMLElement>) {
    const target = e.target as HTMLElement;
    let attr = target.getAttribute("data-attribute-name-here");
    //do something

}



回答4:


Using typescript I've recently learnt of the following approach:

type TabsProps = {
  activeTab: string,
  items: string[],
  setActiveTab: (i: string) => void,
}

const Tabs = ({ items, activeTab, setActiveTab }: TabsProps) => {
  const onClick: React.MouseEventHandler<HTMLElement> = (e) => {
    setActiveTab(e.currentTarget.dataset.id)
    //console.log(e) // <a data-id="0" class="active nav-link">Info</a>
  }

  return (
    <Nav tabs >
        {
            items.map((x, i) => (
                <NavItem key={i}>
                    <NavLink className={activeTab === i.toString() ? 'active' : ''} onClick={onClick} data-id={i}>{x}</NavLink>
                </NavItem>
            ))
        }
    </Nav >
  );
}


来源:https://stackoverflow.com/questions/58634154/react-typescript-get-data-attribute-from-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!