Mysterious syntax onClick={::this.submit}
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?
Answer
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 }
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM