简体   繁体   中英

How to click on a ReactJS wrapping element?

When I click a wrapping element, I'd expect a function to trigger on that wrapping element. Instead it seems to trigger on the most-inner element.

In the case below, clicking on "yo" logs undefined ; clicking on the space between "yo" and "lip" logs 1 ; and clicking on "lip" logs undefined .

I would expect all 3 to log 1 .

import React from 'react';

export default class Foo extends React.Component {
  something = e => {
    e.stopPropagation()
    console.log(e.target.dataset.index)
  }

  render() {
    return (
      <section data-index={1} onClick={this.something} ref={e => { this.section = e }}>
        <h1 style={{ marginBottom: 30 }}>yo</h1>
        <p>lip</p>
      </section>
    )
  }
}

CodeSandbox Demo

import React from 'react';

export default class Foo extends React.Component {
  something = e => {
    e.stopPropagation()
    //console.log(e.target.dataset.index)
    console.log(e.currentTarget.dataset.index)
  }

  render() {
    return (
      <section data-index={1} onClick={this.something} ref={e => { this.section = e }}>
        <h1 style={{ marginBottom: 30 }}>yo</h1>
        <p>lip</p>
      </section>
    )
  }
}

You will get the behavior you want by using e.currentTarget instead of e.target.

The docs for e.currentTarget state :

Identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.

Here is a fork of your codesandbox using e.currentTarget .

import React from 'react';

export default class Foo extends React.Component {
  something = e => {
    e.stopPropagation()
    console.log(e.currentTarget.dataset.index)
  }

  render() {
    return (
      <section data-index={1} onClick={this.something} ref={e => { this.section = e }}>
        <h1 style={{ marginBottom: 30 }}>yo</h1>
        <p>lip</p>
      </section>
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM