【发布时间】:2021-04-26 01:28:49
【问题描述】:
我正在尝试将事件侦听器添加到我的 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',
};
我在这里错过了什么?
【问题讨论】:
-
请问为什么不能直接访问元素?请分享组件的完整细节。
-
fluentui-react定义的iconProps上没有click属性,并且点击事件需要在图标本身上,而不是在它所属的TextField上。所以我需要手动定义它。如果我误解了你,请告诉我。 -
这太奇怪了,我应该看看文档!
-
我有,其他人也有。当
iconProps包含在TextField中时,没有click属性。 -
我为测试做了codeandbox,你的
cursor: 'pointer'有效吗?