REACT.JS点击状态重置

时间:2018-03-14 16:24:29

标签: javascript reactjs state

我正在尝试根据umd-sudoku npm包设置一个Sudoku应用。基本功能是:检查,新游戏,重置板,显示答案。我试图通过

显示瓷砖的正确性
<input className={(props.correct == "true" ? "" : styles.Tile)}>

然而,问题在于,如果我尝试设置新游戏,则布尔值会保留在索引区块上。 initialBoard变量代表实际通过npm包呈现的板,板是保存用户答案的​​变量,这就是为什么我认为通过initialState和setState我将能够访问初始状态。

这是代码的App.js部分:

      class App extends React.Component {
          constructor(props) {
            super(props);
            const initialBoard = sudoku.generate("easy", false);
            const correctAnswers = initialBoard.split("").map(() => true);
            this.state = {
              initialBoard,
              board: initialBoard,
              correctAnswers
            }
          };

          handleSubmit(event) {
            event.preventDefault();
          };

          updateInput(event, index) {
            const tile = event.target.value ? event.target.value[0] : ".";
            this.setState((prev) => ({
              board: prev.board.slice(0, index) + tile.toString() + prev.board.slice(index + 1)
            }));
            event.preventDefault();
          };

          checkIfCorrect() {
            const solution = sudoku.solve(this.state.initialBoard).split("");
            const answer = this.state.board.split("");
            const correctAnswers = answer.map((item, key) => item == solution[key]);

            this.setState({
              correctAnswers
            });
          };

          solveBoard() {
            this.setState({
              board: sudoku.solve(this.state.initialBoard)
            });
          };

          resetBoard() {
            this.setState({
              board: this.state.initialBoard,
            });
            console.log(this.state.correctAnswers);
          };

          newBoard() {
            const initialBoard = sudoku.generate("easy", false);

            this.setState({
              initialBoard: initialBoard,
              board: initialBoard,
            });
          };
render() {
    return (
      <div className={styles.App}>
        <h1>Sudoku</h1>
        <Board
          board={this.state.board}
          initialBoard={this.state.initialBoard}
          fill={this.updateInput.bind(this)}
          correctAnswers={this.state.correctAnswers}
          handleSubmit={this.handleSubmit.bind(this)}
        />
        <div className="buttons">
          <button onClick={this.checkIfCorrect.bind(this)}>Check</button>
          <button onClick={this.newBoard.bind(this)}>New game</button>
          <button onClick={this.solveBoard.bind(this)}>Solve</button>
          <button onClick={this.resetBoard.bind(this)}>Restart</button>
        </div>
      </div>
    )
  }
}

我会很感激任何提示!

0 个答案:

没有答案