reactjs onChange没有拿起最后一个角色

时间:2018-02-23 03:24:32

标签: reactjs onchange event-listener

我无法弄清楚为什么我的onChange事件监听器不接受我表单中的最后一个字符。 (参见image和console.log)onChange Issue

我已阅读有关表格https://reactjs.org/docs/forms.html的反应网站上的文章 我还查看了帖子onChange in React doesn't capture the last character of text

但似乎仍无法找到答案。

这是我的代码:

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

    //this.handleAnswer = this.handleAnswer.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 (/* calculateWinner(squares) || */ squares[i])
    {
      return;
    }

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


    this.setState({
                    squares:      squares,
                    xIsNext:      !this.state.xIsNext,
                    squaresColor: squaresColor,
                    /* num1:          generateRandomNumber(),
                    num2:         generateRandomNumber(), */
                    sqTxt:        sqTxt
                  });

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


  /*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.*/
  handleAnswer(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      

        console.log('num1: ' + num1);
        console.log('num2: ' + num2);
        console.log('userAnswer: ' + userAnswer);
        console.log('correctAnswer: ' + correctAnswer)

        squaresColor[i] = 'purple';


    this.setState({
                    squaresColor: squaresColor
                  })


      if(userAnswer === correctAnswer)
      {
          this.setState({squaresColor: squaresColor});
          console.log('correct');
          squaresColor[i] = 'green';
      }

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

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



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

1 个答案:

答案 0 :(得分:0)

问题是您正在使用onChange。 onChange意味着如果你改变某些东西,它就会发送一个事件。例如在你的代码中:
您已将输入更改为18,但在键入下一个8之前,第一个输入更改为1,因此当您键入18时,它将发送2个事件onChange
在handleAnswer的最后一行,你的代码是:

this.setState({num1: generateRandomNumber(), num2: generateRandomNumber()})

这意味着,在您输入1之后,num 1&amp;的状态为num 2已更改。
我建议你,你必须在条件中移动this.setState({num1: generateRandomNumber(), num2: generateRandomNumber()});,如果用户输入了正确的答案,它将改变num1&amp;的状态。 NUM2。
我的另一个建议是,你可以尝试这种方法
to call onChange event after pressing Enter key