I was plundering some recent react repos this weekend and I came across an example using ES6 class syntax for component composition that went a little something like this.
class MyThing extends Component {
constructor(props) {
super(props)
this.state = {something: 'the thing'}
}
submit() {
// do stuff
}
render() {
<div>
<button onClick={::this.submit}>Fire Submit</button>
</div>
}
}
notice the ::this.submit
in lieu of this.submit.bind(this)
it works, and I cannot find documentation anywhere on this feature, I feel like a crazy person, what is this onClick={::this.doSomethingInsideRenderWithoutDotBind}
syntax called and where can I read more about it?
The double colon is detailed here and is currently an ES7 proposal, so it is not set in stone yet and there is still a lot of debate over it. It also does not allow passing of parameters. so it does have limited use if you have that need.
There is also the 'fat arrow' function option (used on the actual function and not the call to it) that lexically binds to this...
// Basic syntax:
(param1, param2, paramN) => { statements }
(param1, param2, paramN) => expression
// equivalent to: => { return expression; }
// Parentheses are optional when there's only one argument:
(singleParam) => { statements }
singleParam => { statements }
// A function with no arguments requires parentheses:
() => { statements }
// Advanced:
// Parenthesize the body to return an object literal expression:
params => ({foo: bar})
// Rest parameters are supported
(param1, param2, ...rest) => { statements }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With