I'm learning react.
I understand how to share methods between classes with react.
But i'm wondering how it React does it. From the code below, I am wondering how it calls to the handleClick method, how does it bind the this (Board) to the function so when it's called in Square class it points to the Board class and we can set it's state property and such.
In this code below, it sends the Square class an onClick property with an arrow function that contains the Board class method handleClick(i).
When the Square class render method is called, this.props.onClick is passed to the React button element's onClick property and the method(handleClick) inside is called.
The handleClick method points to the Board class when i console.log(this).
Example react code:
class Square extends React.Component {
render() {
return (
<button className="square" onClick={() => this.props.onClick()}>
{this.props.value}
</button>
);
}
}
class Board extends React.Component {
constructor(props){
super(props);
this.state = {
squares: Array(9).fill(null),
};
}
handleClick(i) {
console.log(this);
const squares = this.state.squares.slice();
squares[i] = 'X';
this.setState({squares: squares});
}
renderSquare(i) {
return (
<Square
value={this.state.squares[i]}
onClick={() => this.handleClick(i)}
/>
);
}
How i tried to understand it
I wrote this code below to try and understand it but i get "Uncaught TypeError: Cannot read property 'bind' of undefined". If i remove the bind(), it just console logs the this as "undefined"
class One {
consoleMethod(func, obj){
func().bind(obj);
}
}
class Two {
constructor() {
this.obj1 = new One();
this.func = function(){
console.log(this); // When called: Uncaught TypeError: Cannot read property 'bind' of undefined
}
this.obj1.consoleMethod(this.func, this);
}
}
let obj2 = new Two();
Maybe someone can see the error in my ways and help me understand it.