Reputation: 109
when I use this code :
html : <body>
<button>Click me</button>
<script type="module" src="1.js"></script>
</body>
JS : const btn = document.querySelector('button')
class Events {
constructor() {
console.log(this)
btn.addEventListener('click', this.handleClick)
}
handleClick() {
console.log(this)
}
}
const event = new Events()
"this" = button element
But when I use this code in react:
class Event extends Component {
constructor(props) {
super(props)
this.state = {}
}
handleClick() {
console.log(this)
}
render() {
return (
<div>
<button onClick={this.handleClick}>Click me</button>
</div>
)
}
}
"this" = undefined why 'this' in the javascript event handler is different than react event handler?
Upvotes: 2
Views: 52
Reputation: 1074168
Because React's synthetic event system doesn't call your function with this
set to the DOM element, and the DOM does. It's just the way that React's event handling is written. Instead of yourHandler.call(theDOMElement, eventObject)
it just does yourHandler(eventObject)
. You can read more about it here. If you want to access the DOM element, use the currentTarget
property of the event object:
handleClick(event) {
const element = event.currentTarget;
// ...
}
That's the same element that the DOM uses for this
(and is both a DOM property and a React property). Note that currentTarget
and target
are not the same thing; target
may be an element within the element you hooked the event on, but currentTarget
will always be the element you hooked the event on.
The next question might be what you do about it. That's covered here and here.
Upvotes: 3