3 ms·
It does, you can write this with a Babel preset supporting this feature: class Foo extends Component { state = { foo: '', }; //
by haukur 9y ago
It 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