我计划制作一个按钮,在单击时更新 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
),
});
};
最佳答案
您可以尝试使用 e.currentTarget.value
而不是 e.target.value
。
来自 DOM 事件文档:
Event.currentTarget Identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.
关于javascript - onClick 和 event.target 不工作 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63034274/