In developing React applications with ES6 classes, binding methods to the current object was a common practice in the past. However, can arrow functions be used to permanently bind class functions to an instance, particularly for callback functions?
Previously, one would bind methods using syntax like:
class SomeClass extends React.Component { constructor(){ this.handleInputChange = this.handleInputChange.bind(this) } }
Attempting to use arrow functions instead:
class SomeClass extends React.Component { handleInputChange (val) => { console.log('selectionMade: ', val); } }
results in errors.
The syntax for using arrow functions as class methods is slightly different. An equals sign is needed after the property name:
class SomeClass extends React.Component { handleInputChange = (val) => { console.log('selectionMade: ', val); } }
This feature is experimental and requires the transform-class-properties Babel plugin to compile:
{ "plugins": [ "transform-class-properties" ] }
Install the plugin via npm:
npm install --save-dev babel-plugin-transform-class-properties
With experimental features enabled, passing SomeClass.handleInputChange as a callback function will be scoped to the class instance, not the window object.
For more information, refer to the proposal for Class Fields and Static Properties.
The above is the detailed content of Can Arrow Functions Permanently Bind Class Methods in ES6 React Components?. For more information, please follow other related articles on the PHP Chinese website!