Sunday, May 19, 2024
179
rated 0 times [  181] [ 2]  / answers: 1 / hits: 139797  / 9 Years ago, sat, july 11, 2015, 12:00:00

I'm new to using ES6 classes with React, previously I've been binding my methods to the current object (show in first example), but does ES6 allow me to permanently bind a class function to a class instance with arrows? (Useful when passing as a callback function.) I get errors when I try to use them as you can with CoffeeScript:



class SomeClass extends React.Component {

// Instead of this
constructor(){
this.handleInputChange = this.handleInputChange.bind(this)
}

// Can I somehow do this? Am i just getting the syntax wrong?
handleInputChange (val) => {
console.log('selectionMade: ', val);
}


So that if I were to pass SomeClass.handleInputChange to, for instance setTimeout, it would be scoped to the class instance, and not the window object.


More From » arrow-functions

 Answers
16

Your syntax is slightly off, just missing an equals sign after the property name.



class SomeClass extends React.Component {
handleInputChange = (val) => {
console.log('selectionMade: ', val);
}
}


This is an experimental feature. You will need to enable experimental features in Babel to get this to compile. Here is a demo with experimental enabled.



To use experimental features in babel you can install the relevant plugin from here. For this specific feature, you need the transform-class-properties plugin:



{
plugins: [
transform-class-properties
]
}


You can read more about the proposal for Class Fields and Static Properties here





[#65841] Thursday, July 9, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckinleyi

Total Points: 121
Total Questions: 100
Total Answers: 109

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
;