使用 `addEventListener` 将点击事件添加到 React 组件中的图标
Using `addEventListener` to add click event to icon within React component
我正在尝试向我的 React 应用程序中的图标添加一个事件侦听器,以便我可以在特定地单击该图标时触发一个功能(单击周围的 TextField
是不够的)。我需要手动执行此操作,因为 fluentui-react
元素上没有 click
属性。
到目前为止,虽然我可以根据 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 的“Clear icon clicked!”不会打印到控制台。
请注意,使用 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 下图标的指针事件
我假设您可以通过为指针事件设置为 'auto' 的 iconProps 提供内联样式来覆盖此行为,然后像往常一样传递 onClick,它看起来像这样:
<TextField iconProps={style: {pointerEvents: 'auto'}, onClick: () => {..}} />
我正在尝试向我的 React 应用程序中的图标添加一个事件侦听器,以便我可以在特定地单击该图标时触发一个功能(单击周围的 TextField
是不够的)。我需要手动执行此操作,因为 fluentui-react
元素上没有 click
属性。
到目前为止,虽然我可以根据 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 的“Clear icon clicked!”不会打印到控制台。
请注意,使用 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 下图标的指针事件
我假设您可以通过为指针事件设置为 'auto' 的 iconProps 提供内联样式来覆盖此行为,然后像往常一样传递 onClick,它看起来像这样:
<TextField iconProps={style: {pointerEvents: 'auto'}, onClick: () => {..}} />