我计划制作一个按钮,以在单击时更新state
。在按钮内部有一个img
和div
。当我单击按钮时,触发上的onClick
,但是当我单击img
或div
时,没有触发。当我希望用户单击按钮上的任意位置(包括img
和div
)时,任何人都知道如何解决此问题。
我的jsx代码是:
<div
className={
'flex flex-row flex-wrap justify-around border-2 rounded border-dashed'
}>
{categoryLeft.map((category) => (
<button
onClick={this.addCategory}
type='button'
value={category}
name={category}
className={
'flex bg-teal-600 my-2 mx-1 w-auto h-auto hover:bg-teal-400 text-white font-bold px-1 rounded'
}>
<div className={'self-center'} value={category}>
{category}
</div>
<img
className={'float-right ml-1 self-center w-5 h-5'}
value={category}
src={CloseImg}
/>
</button>
))}
</div>
</div>
我的方法是:
addCategory = (e) => {
console.log(e.target);
console.log(this.state.categoryLeft);
this.setState({
categoryUsed: [...this.state.categoryUsed, e.target.value],
categoryLeft: this.state.categoryLeft.filter(
(cat) => cat !== e.target.value
),
});
};
答案 0 :(得分:2)
您可以尝试使用e.currentTarget.value
代替e.target.value
。
来自DOM事件文档:
Event.currentTarget标识事件的当前目标,因为事件遍历DOM。它始终是指事件处理程序所附加的元素,而不是event.target,它标识发生事件的元素。