javascript - onClick 和 event.target 不工作 react

标签 javascript reactjs onclick dom-events

我计划制作一个按钮,在单击时更新 state。在按钮内部有一个 imgdivonClick 在我点击按钮时触发,但在我点击 imgdiv 时触发。任何人都知道如何解决这个问题,因为我希望用户单击按钮上的任意位置(包括 imgdiv)。 我的 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/

相关文章:

javascript - Google Analytics 报告 v4(过滤器)

javascript - 执行所有脚本后如何获得生成的 HTML?

javascript - 如何在javascript中设置定时器

javascript - react 分页选择切换类名

javascript - 在哪里存储状态以使 React 组件更可重用

javascript - 如何使用jquery检测动态添加的点击元素?

javascript - jQuery - 通过多个不同的选择器进行选择

javascript - 访问隐藏元素的宽度和高度

jquery - 需要帮助才能通过更改 onClick 背景位置使链接处于事件状态

javascript - 添加到 document.body 的 innerHTML 导致 jQuery .on() 找不到它的目标