【问题标题】:react: onClick - get only the clicked element, not the childrenreact: onClick - 只获取被点击的元素,而不是子元素
【发布时间】:2018-10-02 09:48:52
【问题描述】:

我有一个按钮,这个按钮里面是一个字体很棒的 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

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

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

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

【讨论】:

  • Facepalm...这绝对是正确的。谢谢
【解决方案2】:

可以通过多种方式完成。我更喜欢 CSS 的方式,将 pointer-events : none 应用于子 span

代码笔:https://codepen.io/imsontosh/pen/mzeqNx

button { 
  background: #eee;
  border: 1px solid #ddd; 
  width: 150px;
  span{
    pointer-events:none;
  }
}

【讨论】:

    猜你喜欢
    • 2013-08-22
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    相关资源
    最近更新 更多