by dmitriid · 9y ago · 0 comments
--- quote ---
With the ESnext field declarations proposal, the above example can be written as
class Counter extends HTMLElement {
x = 0;
clicked() {
this.x++;
window.requestAnimationFrame(this.render.bind(this));
}
constructor() {
super();
this.onclick = this.clicked.bind(this);
}
connectedCallback() { this.render(); }
render() {
this.textContent = this.x.toString();
}
}
window.customElements.define('num-counter', Counter);
--- end quote ---this.onclick = this.clicked.bind(this); etc. are all still there
class Foo extends Component {
state = {
foo: '',
};
// The arrow function here is what you're looking for.
onChange = ({ target }) => {
this.setState({
// You can of course use `foo` directly as the key if you just have the one input.
[target.name]: target.value,
});
};
render () {
return <input type="text" name="foo" value={this.state.foo.value} onChange={this.onChange} />;
}
}Also, your example is not equivalent to either the complaint in the original comment or to the code snippet I quoted
Also: React has been binding event handlers to `this` since forever without presets (update: only in React.creatClass though)
Yes, with public fields you can write
handleClick = () => {
// ...
}
and it works like if you bound it in the constructor.Hope this helps.
handleClick = () => {...}
This is a shitty workaround that abuses class fields and arrow functions