Answer the question
In order to leave comments, you need to log in
How does an event handler work in React?
There is a code:
function Square(props) {
return (
<button
className="square"
onClick={props.onClick}
>
{props.value}
</button>
);
}
class Board extends React.Component {
state = {
squares: Array(9).fill(null)
}
handleClick(i) {
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)}
/>
);
}
render() {
const status = 'Next player: X';
return (
<div>
<div className="status">{status}</div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
так
onClick={props.onClick}
а не так
onClick={props.onClick()}
Answer the question
In order to leave comments, you need to log in
JavaScript code is written in curly brackets. Accordingly, if you write onClick={props.onClick()}
, then this will be a function call, and the result of this call will be assigned to the onClick
button property. And it needs to be a function, which is achieved by the line onClick={props.onClick}
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question