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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…