reactjs-回调函数在输入键被按下时仍然没有更新背景颜色

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了reactjs-回调函数在输入键被按下时仍然没有更新背景颜色相关的知识,希望对你有一定的参考价值。

我在这里阅读了反应文档和示例:When to use React setState callback

我正在尝试使用回调来让setState()立即更新。但我的背景颜色,或squaresColor[i]仍然没有更新。

console.log(squaresColor[i])正在输出undefined: green。绿色是正确的,但关键undefined

我试图... setState(squaresColor: squaresColor),但按下回车键后,背景仍然没有改变。无论出于何种原因,我使用相同的setState用不同的方法,handleClick()。这被称为异步调用,它工作正常。

那么为什么handleKeyPress中的背景颜色没有更新?我不应该使用州进行此更新吗?

我的代码:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';



/*stop clicking ability after clicking a problem (prevent default) and enable it when submit is done.*/

/*  let btnStyle = {
        backgroundColor: 'green'
    } */

/*we also changed onClick={() => props.onClick()} to just onClick={props.onClick},
 as passing the function down is enough for our example. Note that onClick={props.onClick()}
 would not work because it would call props.onClick immediately instead of passing it down.*/



class  Square extends React.Component
{
    render()
    {
        return (
                 <button className="square" onClick = {this.props.onClick} style = {{backgroundColor: this.props.backgroundColor}}>
                    {this.props.value}
                    {this.props.txt}
                </button>
            );
    }

}

class Board extends React.Component
{
    constructor(props)
    {
    super(props);
    this.state =
    {
      squares: Array(25).fill(null),
      xIsNext: true,
      squaresColor: Array(25).fill('null'),
      num1: generateRandomNumber(),
      num2: generateRandomNumber(),
      ans:  function(a,b){return(a * b);},
      sqTxt: Array(25).fill(null),
      next: true
    };

    //this.handleKeyPress = this.handleKeyPress.bind(this);

  }

  handleClick(i)
  {
    const squares = this.state.squares.slice();           // makes a mutable copy of the array
    const squaresColor = this.state.squaresColor.slice(); // makes a mutable copy of the array
    const sqTxt = this.state.sqTxt.slice(); // makes a mutable copy of the array
    if (!(this.state.next) || squares[i])
    {
      return;
    }

    squaresColor[i] = 'blue';
    sqTxt[i] =  <input onKeyPress = {(e,i) => this.handleKeyPress(e, i)} className = 'answer-input' type = 'text' name = 'answer' />;


    this.setState({
                    squares:      squares,
                    squaresColor: squaresColor,
                    sqTxt:        sqTxt,
                    next:         false
                  });

    console.log(this.state.squaresColor[i]);

    squares[i] = this.state.num1 + ' X ' + this.state.num2;

    return this.state.next;

  }


  /*When an event is invoked, it will be passed an event object as it's first argument. You can name evt whatever you like. Common names are e evt and event.*/
  handleKeyPress(e, i)
  {
      const userAnswer = parseInt(e.target.value, 10);
      const num1 = this.state.num1;
      const num2 = this.state.num2;
      const correctAnswer = num1 *  num2;
      const squaresColor = this.state.squaresColor.slice();           // makes a mutable copy of the array      

       if(e.key === 'Enter')
      { 
        squaresColor[i] = 'green';

          if(userAnswer === correctAnswer)
          {
              this.setState({
                                /* squaresColor: */ squaresColor,
                                next:         true,
                            }/* ,  function() 
                                {
                                    console.log(this.state.squaresColor);
                                    this.setState(squaresColor: squaresColor);
                                } */);

              //create new numbers for next problem
             this.setState({num1: generateRandomNumber(), num2: generateRandomNumber()});
          }

          else
          {
              console.log('incorrect');
          }  
      }
  }



  renderSquare(i)
  {
    return (
      <Square
        value={this.state.squares[i]}
        onClick = {() => this.handleClick(i)}
        backgroundColor = {this.state.squaresColor[i]}
        txt = {this.state.sqTxt[i]}
      />
    );
  }

  render()
  { 
    return (
      <div className = 'all-rows'>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
          {this.renderSquare(3)}
          {this.renderSquare(4)}
        </div>
        <div className="board-row">
          {this.renderSquare(5)}
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
          {this.renderSquare(9)}
        </div>
        <div className="board-row">
          {this.renderSquare(10)}
          {this.renderSquare(11)}
          {this.renderSquare(12)}
          {this.renderSquare(13)}
          {this.renderSquare(14)}
        </div>
        <div className="board-row">
          {this.renderSquare(15)}
          {this.renderSquare(16)}
          {this.renderSquare(17)}
          {this.renderSquare(18)}
          {this.renderSquare(19)}
        </div>
        <div className="board-row">
          {this.renderSquare(20)}
          {this.renderSquare(21)}
          {this.renderSquare(22)}
          {this.renderSquare(23)}
          {this.renderSquare(24)}
        </div>
      </div>
    );
  }
}


class Game extends React.Component
{
  render() {
    return (
      <div className="game">
        <div className="gxame-board">
          <Board />
        </div>
        <div className="game-info">
        </div>
      </div>
    );
  }
}


ReactDOM.render(
  <Game />,
  document.getElementById('root')
);


function generateRandomNumber()
{
    return Math.floor(Math.random() * 10);
}
答案

你不需要再次打电话给setState。你应该重写这个部分,如:

if(e.key === 'Enter') { 
  squaresColor[i] = 'green';

  if(userAnswer === correctAnswer) {
      this.setState({
          squaresColor,
          next: true,
          num1: generateRandomNumber(),
          num2: generateRandomNumber()
      }, () => {
          console.log(this.state);
      });
  } else {
      console.log('incorrect');
  }  
}

并且不要评论this.handleKeyPress = this.handleKeyPress.bind(this);

以上是关于reactjs-回调函数在输入键被按下时仍然没有更新背景颜色的主要内容,如果未能解决你的问题,请参考以下文章

如果只有一个键被按下,如何触发动作?

JavaScript键盘鼠标事件处理

检测功能键被按下的最佳方法是啥?

按键被按下时如何增加速度变量?

JS事件

JS事件