使用 `addEventListener` 将点击事件添加到 React 组件中的图标

问题描述

我正在尝试向我的 React 应用程序中的图标添加一个事件侦听器,以便我可以在单击该图标时触发一个函数(单击周围的 TextField 是不够的)。我需要手动执行此操作,因为 click 元素上没有 fluentui-react 属性

到目前为止,虽然我可以根据我的 console.log 看到已选择了正确的 DOM 元素,但当我单击该图标时,没有任何反应。

我正在 componentDidUpdate() 中处理此问题,如下所示:

  componentDidUpdate() {
    const node = ReactDOM.findDOMNode(this);
    if (this.props.sessionsWithNotes.length) {
      if (node instanceof HTMLElement) {
        const child = node.querySelector('i');
        console.log('child: ',child); // I see this in the console
        child.addEventListener('click',() => console.log("Clear icon clicked!")); // This does not print to the console upon click of the icon
      }
    }
  }

明确地说,我登录到控制台的 child 显示了这一点:

<i data-icon-name="clear" aria-hidden="true" class="icon-167"></i>

这是正确的图标元素。但是,当我看到控制台中显示内容后单击它时,没有任何反应 - 即我的 console.log 的“已单击清除图标!”不会打印到控制台。

注意,使用 react-fluent-ui 的相关 JSX 块如下所示:

  <TextField
    label="ID:"
    defaultValue={this.props.filters.id}
    onChange={this.onFilterById}
    styles={{ root: { maxWidth: 300 } }}
    borderless
    underlined
    iconProps={iconProps}
  />

iconProps 看起来像这样:

const iconProps = {
  iconName: 'clear',cursor: 'pointer',};

在这里遗漏了什么?

解决方法

似乎他们禁用了 TextField 下图标的指针事件

https://github.com/microsoft/fluentui/blob/master/packages/react-internal/src/components/TextField/TextField.styles.tsx

我假设您可以通过向 iconProps 提供内联样式并将指针事件设置为“自动”来覆盖此行为,然后像往常一样传递 onClick,它看起来像这样:

<TextField iconProps={style: {pointerEvents: 'auto'},onClick: () => {..}} />