javascript - react : onClick - get only the clicked element, 而不是 child

标签 javascript reactjs

我有一个按钮,在这个按钮里面是一个 fontawesome svg。 监听器只在按钮上,不在 svg 上。虽然,当我点击 svg 时,event.target 不是按钮。

但我只需要按钮作为目标。

代码如下:

const icon = '<svg aria-hidden="true" data-prefix="fas" data-icon="paragraph" class="svg-inline--fa fa-paragraph fa-w-14 " role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M408 32H177.531C88.948 32 16.045 103.335 16 191.918 15.956 280.321 87.607 352 176 352v104c0 13.255 10.745 24 24 24h32c13.255 0 24-10.745 24-24V112h32v344c0 13.255 10.745 24 24 24h32c13.255 0 24-10.745 24-24V112h40c13.255 0 24-10.745 24-24V56c0-13.255-10.745-24-24-24z"></path></svg>';

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  handleClick(event) {
    event.stopPropagation();
    console.log(event.target);
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          <span dangerouslySetInnerHTML={{__html: icon}} />
        </button>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

我写了一个小笔:https://codepen.io/DaFunkyAlex/pen/aRvVjd

最佳答案

您应该使用:event.currentTarget,它始终是监听事件的对象。

event.target 是收到点击的实际目标。

关于javascript - react : onClick - get only the clicked element, 而不是 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52605917/

相关文章:

javascript - 在 IE 中使用 JS、HTML 和 CSS 自定义文件上传

javascript - 在 ember 中记录单选按钮的值

javascript - 获取 url 到 React 组件

reactjs - 动态更改 Redux-toolkit Global Store 中的 Material UI 主题

javascript - 如何在 React JS 中获取元素边距

javascript - Bootstrap 导航栏切换按钮在移动设备中不可见

javascript - jQuery .change() 事件只触发一次

javascript - react 访问状态

javascript - Normalizr 转换模式的麻烦

javascript - JQuery:在ajax生成的事件上注册事件