【问题标题】:reactjs onChange not picking up last characterreactjs onChange没有拿起最后一个字符
【发布时间】:2018-08-03 02:00:11
【问题描述】:

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

我已经阅读了 react 网站上关于表单 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);
}

【问题讨论】:

    标签: reactjs onchange event-listener


    【解决方案1】:

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

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

    这意味着,在您输入 1 后,num 1 和 num 2 的状态发生了变化。
    我建议你,你必须在条件中移动this.setState({num1: generateRandomNumber(), num2: generateRandomNumber()});,如果当用户输入正确答案时,它会改变num1和num2的状态。
    我的另一个建议,你可以试试这个方法
    to call onChange event after pressing Enter key

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 2013-10-12
      • 2021-01-23
      • 2018-12-05
      • 1970-01-01
      • 2020-12-28
      • 2016-05-31
      相关资源
      最近更新 更多