I am trying to add an event listener to an icon in my React app, so that I can fire a function upon click of the icon specifically (a click on the surrounding TextField
will not suffice). I need to do this manually, because there is no click
property on the fluentui-react
element.
So far, while I can see based on my console.log that the correct DOM element has been selected, when I click the icon, nothing happens.
I am handling this in componentDidUpdate()
, like so:
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
}
}
}
To be clear, the child
that I am logging to the console shows this:
<i data-icon-name="clear" aria-hidden="true" class="icon-167">?</i>
So that is the correct icon element. However, when I click on it after I see that show up in the console, nothing happens - i.e., my console.log of "Clear icon clicked!" doesn't get printed to the console.
Note, the relevant JSX block, that makes use of react-fluent-ui
, looks like this:
<TextField
label="ID:"
defaultValue={this.props.filters.id}
onChange={this.onFilterById}
styles={{ root: { maxWidth: 300 } }}
borderless
underlined
iconProps={iconProps}
/>
And iconProps
looks like this:
const iconProps = {
iconName: 'clear',
cursor: 'pointer',
};
What am I missing here?
question from:
https://stackoverflow.com/questions/65830612/using-addeventlistener-to-add-click-event-to-icon-within-react-component 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…