event.target
gives a li
element because the browser works with the DOM, not the virtual structure that React keeps in memory.
There is no MenuItem
element on the rendered page. Instead, there's the elements that are rendered by MenuItem
s.
Click events come from actual DOM elements like div, input, li. Why not from MenuItem? Because there's no <MenuItem>
on the page. When you click on the elements, you click on <li>
s, not <MenuItem>
s.
What you want to do is achievable by setting an "imaginary" click handler on the virtual <MenuItem>
:
<VirtualElement onClick={virtualClickHandler} />
Then, when rendering the real DOM element <li>
, the VirtualElement will set on it a real click handler:
class VirtualElement {
realClickHandler (e) { // Let's assume you've bound this in the constructor
// do stuff with "e" and "this.props"
}
render () {
return <li onClick={realClickHandler} />
}
}
Now, realClickHandler
's scope contains this
and e
. This means, it can read both the state & (virtual) props of the VirtualElements and the event object.
The final part - the only thing left is the virtualClickHandler
. Where does it reside? In this.props
. Because when earlier you said <VirtualElement onClick={virtualClickHandler} />
, this onClick handler gets written on the props
object of the VirtualElement.
What you want to do is call the virtualClickHandler from the realClickHandler, which sees both the event and the this object:
realClickHandler (e) {
// Here you can tell the virtualClickHandler whatever it needs to know:
this.props.onClick({
event: e,
key: this.props.key
});
}