Can't use `this` in JSX
Closed this issue · 3 comments
odzb commented
If I want to use this
in my JSX like this:
<div onMouseDown={this.handleMouseDown.bind(this)}>
Then it just won't work, because generated code gets enclosed in an IIFE which is not an arrow function.
treycordova commented
Alright, my solution to this problem is the following:
const element = <div onClick={this.onClick.bind(this)} />
Transpiles to
const element = function() {
var $$a = document.createElement('div');
$$a.addEventListener(this.onClick.bind(this));
return $$a;
}.call(this);
I'd like to point out .call(this)
. That'll pipe through this
anywhere JSX is used. It'll be up to the user to pipe it through larger expressions. That can be accomplished using arrow functions.
const element = (
<ul>
{[1, 2, 3].map(() => {
return <li onClick={this.onClick.bind(this)} />
}}
</ul>
)
odzb commented
Looks good to me, thank you!
treycordova commented
Closing this up with the release of 4.0.0. Thanks again!