简体   繁体   中英

Wrong event.target when clicking button child element

I have the following element representing a button in a survey:

<button name={id} value={value} onclick={handleChoiceClick} className="choice__button">
   <img src={image} className="choice__button-image"/>
   <span className="choice__button-title">Button title</span>
</button>

The handleChoiceClick function triggers the handleChange function and stores some data by the button's name and value:

const handleChoiceClick = (e) => {
   handleChange(e.target.name, e.target.value);
};

This works fine, but when I click one of the child elements inside the button (image or span) the handleChoiceClick function gets another event.target as a parameter and the name and values are undefined.

What is the best way to solve this issue? Checking the event.target inside the handleChoiceClick or is there a simpler way?

If you want the element that you hooked the event on, use event.currentTarget rather than event.target . In your case, that will always be the button element.

const handleChoiceClick = (e) => {   
   var buttonElement = e.target.closest('.choice__button')
   handleChange(buttonElement.name, buttonElement.value);
};

This can give you the name and value of the required button although the target is any other element inside the button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM