I'm having a bit of trouble understanding why classes in react function differently that plain js. Or am I missing something?
In the code I have, I understand that Header inherits the properties of 'props' so thanks to the constructor, I can use this.name inside the jsx. And als, in Header.proto resides the function doSomething. But when I call the function doSomething, the function can be called but doesn't have any access to 'this.name'. In plain js, it would have worked. so what's going on?
Why does binding / using an arrow function solve the problem?
Thanks in advance!
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export class Header extends Component {
constructor(props) {
super();
this.name = props.name;
}
doSomething() {
this.name = 5;
}
render() {
return(
<div>
<button onClick={this.doSomething}></button>
</div>
);
}
}