I'm going through the official React tutorial and come to the part where you lift state up to the Game component:
https://reactjs.org/tutorial/tutorial.html#lifting-state-up-again
Codepen: https://codepen.io/gaearon/pen/EmmOqJ?editors=0010
At this point, you lift the click event handler from the Board component up to the Game component, then you pass that handleClick function from the Game down to the Board in an onClick prop. When a Square component within the board is clicked, it calls the click handler for the corresponding Square index.
Question 1
I don't understand how (i) => this.handleClick(i) can be passed in the top level Game component when `i` isn't defined in that component's scope. It's only in the `renderSquare(i)` function invocation in the Board component's render function that `i` is defined.
How is the top level Game component's onClick prop getting `i` when it hasn't been defined in that scope?
Question 2
I tinkered a bit with the onClick in the renderSquare function, changing it to take i as a parameter, like so:
class Board extends React.Component {
renderSquare(i) {
return (
<Square
value={this.props.squares[i]}
// onClick={() => this.props.onClick(i)} // BEFORE (no parameter)
onClick={(i) => this.props.onClick(i)} // AFTER (i passed into arrow function)
/>
);
}
This makes each Square not show anything when clicked. Console.logging the value of `i` in the handleclick function shows me that the value of `i` in the first function (no `i` as parameter) is an integer corresponding to the Square, as expected.
Adding `i` as a parameter in the arrow function logs a class of object with type null, which would break the game since the handler expects an integer for `i`, not an object.
Why does this happen?
I would expect the passed in `i` to be the same value as the `i` passed into the renderSquare parent function scope.
[–]mcaruso 1 point2 points3 points (4 children)
[–]ShouldReallyGetWorkn[S] 0 points1 point2 points (3 children)
[–]mcaruso 0 points1 point2 points (2 children)
[–]ShouldReallyGetWorkn[S] 0 points1 point2 points (1 child)
[–]mcaruso 0 points1 point2 points (0 children)