K
K
kirillleogky2020-01-22 20:49:47
JavaScript
kirillleogky, 2020-01-22 20:49:47

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>
    );
  }
}

Why is onClick={props.onClick} written without brackets in the Square(props) function??
так 
onClick={props.onClick}

а не так
onClick={props.onClick()}

If you look at this, then when on the handler, you need to call it ( https://learn.javascript.ru/introduction-browser-e...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Klimenko, 2020-01-22
@kirillleogky

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 onClickbutton 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 question

Ask a Question

731 491 924 answers to any question