Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

reactjs - Using `addEventListener` to add click event to icon within React component

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Seems like they disabled the pointer-events for icon under TextField

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

i assume you can override this behavior by providing inline style to iconProps with pointer-events set to 'auto' and then just pass onClick as you normally would, it would look like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...