4 ms·
The framework and language of champions this.handleChange = this.handleChange.bind(this);
by revelation 9y ago
The framework and language of champions
this.handleChange = this.handleChange.bind(this);
- rmrfrmrf 9y agoEvent binding is ugly in every language, though...
- ralmidani 9y agoI agree this syntax is awkward, tedious, and ceremonious. But if your components are ES6 classes, fat-arrow methods let you avoid it.
- danabramov 9y agoWhich is our colleagues at Facebook worked on the class fields proposal that addresses this elegantly :-) https://github.com/tc39/proposal-class-fields https://github.com/tc39/proposal-class-fields Changes to the language take time, but then they benefit everyone and not just a particular library.
- dmitriid 9y agoThe proposal does nothing to remove the awkward binding everywhere, unless I'm mistaken. Here's the verbatim quote from the proposal: --- 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
- haukur 9y agoIt does, you can write this with a Babel preset supporting this feature: 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} />; } }
- dmitriid 9y agoThen either the readme in the proposal is wrong or the unknown babel preset is wrong 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)
- danabramov 9y agoThe proposal README is written for TC39 and not React users, so it doesn't address the problems React users face. Yes, with public fields you can write handleClick = () => { // ... } and it works like if you bound it in the constructor. Hope this helps.
- dmitriid 9y agoIt’s not just React-specific. I was correct: the proposal does exactly nothing to make sure class methods are bound to class instances. handleClick = () => {...} This is a shitty workaround that abuses class fields and arrow functions
- s4m3 9y agoYou can use class properties instead