onClick 和 event.target 不工作反应

onClick and event.target not working react

我计划制作一个按钮,在单击时更新 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.