Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - div's id attribute is undefined/not getting captured onClick in a react app

I'm mapping data from the api response and rendering multiple divs out of it. Along with that I'm assigning a unique id from the response to the id attribute of each div like this:

...lists.map(list => {
  return (
  <div className='one' key={list.id} id={list.id} onClick={this.handleClick}>
    <div className='two'>
      <p>Hello World</p>
      <span>Foo Bar</span>
    </div>
  </div>
)
})

handleClick = (e) => {
  console.log(e.target.id)
  // other stuff
}

The Problem:

Whenever the outer div (className='one') is clicked the console logs undefined. However, if I assign the id value to the inner div (className='two') it logs the value of id only if the click is made within the dimensions of the inner div. Same is the case with the <span> and <p> tags.

Basically, the onClick returns a different target on clicking different html elements.

Expected result:

Clicking the parent div or anywhere inside that div should always return the value of the id attribute of the parent div.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The thing is when you define onClick on the topMost parent, you need to use e.currentTarget.id instead of e.target.id since e.target will give you the element on which you clicked rather then the parent on which onClick listener is defined

class App extends React.Component {
state = {
  lists: [{id: 1}, {id: 2}, {id:3}]
}
render() {
  return (
    <div>
      {this.state.lists.map(list => {
          console.log(list.id)
          return (
          <div className='one' key={list.id} id={list.id} onClick={this.handleClick}>
            <div className='two'>
              <p>Hello World</p>
              <span>Foo Bar</span>
            </div>
          </div>
        )
       })
       }
    </div>
  )
}

handleClick = (e) => {
  console.log(e.currentTarget.id)
  
  // other stuff
}

}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...