In a react script, for every function in both the parent and child components we must have this magic line using .bind(this)
in the constructors:
this.nameOfFunction = this.nameOfFunction.bind(this);
For example:
// Parent with a incrementNumberTurns() function: this.incrementNumberTurns = this.incrementNumberTurns.bind(this); // Child with a handleClick() function: this.handleClick = this.handleClick.bind(this)
Here is an example from the parent component constructor of my tic-tac-toe game. Every function name needs to be initialized in the constructor this way:
class Game extends React.Component { constructor(props) { super(props) this.incrementNumberTurns = this.incrementNumberTurns.bind(this); this.populateXLocations = this.populateXLocations.bind(this); this.cellClicked = this.cellClicked.bind(this); this.updateBoard = this.updateBoard.bind(this); this.newGame = this.newGame.bind(this); this.changeTurns = this.changeTurns.bind(this); this.setGameInProgress = this.setGameInProgress.bind(this); this.setCatsGame = this.setCatsGame.bind(this);
See:
https://github.com/chris-relaxing/react-tic-tac-toe/blob/master/tic-tac-toe.js
Here is what the React documentation says about .bind(this)
:
For more information about .bind(this)
, see:
https://stackoverflow.com/questions/29732015/value-of-this-in-react-event-handler
http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html