简体   繁体   中英

How to disable a button once clicked in JSX, ReactJs?

I'm making a 2 player tic tac toe game and I can not find out how to prevent a player from clicking on a square that has already been clicked on.

Currently if a player clicks on a X/O already present it changes the state to O/X. I want to disable that.

Board.js

import React, { useState } from 'react'
import Square from './Square'

export default function Board () {

  const [xIsNext, setXIsNext] = useState(true);
  const [squares, setSquares] = useState(Array(9).fill());

  const renderSquare = (i) => {
    return <Square 
      squares={squares[i]} 
      handleClick={()=>handleClick(i)}
    />;
  }

  const handleClick = (i) => {
    const newSquares = squares.slice();
    newSquares[i] = xIsNext ? 'X' : 'O';
    setSquares(newSquares);
    setXIsNext(!xIsNext);
  }

  const status = 'Next player: ' + (xIsNext ? 'X' : 'O');

  return (
    <div>
      <div className="status">{status}</div>
      <div className="board-row">
        {renderSquare(0)}
        {renderSquare(1)}
        {renderSquare(2)}
      </div>
      <div className="board-row">
        {renderSquare(3)}
        {renderSquare(4)}
        {renderSquare(5)}
      </div>
      <div className="board-row">
        {renderSquare(6)}
        {renderSquare(7)}
        {renderSquare(8)}
      </div>
    </div>
  );
}

Square.js

import React from "react";

export default function Square ({ squares, handleClick, disabled })  {
  return (
    <button className="square" onClick={()=>handleClick()} disabled={disabled}>
      {squares}
    </button>
  );
}

I've used state to prevent clicking on a button already pressed, but it disables all the button in the game rather than just the one that was pressed.

You should add the disabled prop to your Square with a value based on if the square has data or not, eg

const renderSquare = (i) => {
    return <Square 
      squares={squares[i]} 
      handleClick={()=>handleClick(i)}
      disabled={!!squares[i]}
    />;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM