[W]hen we use ES6 class all its methods are not automatically bound to the instances created through that class?
They're not strictly bound, no. That means you can still use them without an instance of that class. This is true for all of ES2015+.
class A {
log() {
console.log(this.value);
}
}
let a = new A();
let b = { value: 'B' };
a.log.call(b);
...apart from React...
Nothing about React changes how methods are bound. What people mean when they talk about that is that the methods aren't lexically bound this will not give you what you expect:
class MyComponent extends React.Component {
constructor() {
super();
this.value = 'MyComponent';
}
showValue() {
console.log(this.value);
}
render() {
return (
<button onClick={this.showValue}>Click Me</button>
);
}
}
Because showValue
has not been bound to the instance of MyComponent
, it will value to retrieve the this.value
property.
To make this work correctly you can do the following with existing syntax:
class MyComponent extends React.Component {
constructor() {
super();
this.value = 'MyComponent';
this.showValue = this.showValue.bind(this);
}
showValue() {
console.log(this.value);
}
render() {
return (
<button onClick={this.showValue}>Click Me</button>
);
}
}
or with field declarations (this is, as of Oct. 19 2017, currently proposed and is not a part of the core language):
class MyComponent extends React.Component {
constructor() {
super();
this.value = 'MyComponent';
}
showValue = () => {
console.log(this.value);
}
render() {
return (
<button onClick={this.showValue}>Click Me</button>
);
}
}