【问题标题】:State is being updated but not displaying [duplicate]状态正在更新但不显示[重复]
【发布时间】:2025-12-27 05:10:12
【问题描述】:

我有一个文本框,一个可点击按钮和另一个不可点击按钮,用于在按下可点击按钮时显示一个数字我希望文本框中的值显示在另一个按钮中。 this.state 正在更新但未显示。

这是我第一次使用 react,请给我任何反馈。

class GameBoard extends React.Component {
  render() {
    return (
      <div className="gameBoard">
        <table>
          <tbody>
            <tr>
              <th><input id="trips" className="inp"></input></th>
              <th><button onClick={() => this.props.onClick("trips")}>place bet</button></th>
              <th><button className="bettingSquere" >{this.props.game.trips}</button></th>
            </tr>
          </tbody>
        </table>
      </div>
    );
}}

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      trips: 0,
    };
  }

  handleClick(type) {
    var state = this.state;
    state.trips=document.getElementById("trips").value;
    this.state=state;
  }

  render() {
    return (
      <div align="center">
        <GameBoard game={this.state} onClick={i => this.handleClick(i)} />
      </div>
    );
  }
}

export default App;

【问题讨论】:

  • 更新状态时需要使用this.setState方法。不能通过直接修改来改变状态。

标签: javascript reactjs


【解决方案1】:

您应该再次阅读文档。不要像在 handleClick 方法中那样直接改变或改变你的状态。您应该使用setState 方法来更新您的状态。此外,您不需要像那样更改输入值。您可以使用onChance 并在那里设置另一个状态。

class GameBoard extends React.Component {
  state = {
    inputValue: null
  };

  handleInputChance = e =>
    this.setState({
      inputValue: e.target.value
    });

  handleClick = () => this.props.onClick(this.state.inputValue);

  render() {
    return (
      <div className="gameBoard">
        <table>
          <tbody>
            <tr>
              <th>
                <input
                  id="trips"
                  className="inp"
                  onChange={this.handleInputChance}
                />
              </th>
              <th>
                <button onClick={this.handleClick}>place bet</button>
              </th>
              <th>
                <button className="bettingSquere">{this.props.trips}</button>
              </th>
            </tr>
          </tbody>
        </table>
      </div>
    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      trips: 0
    };
  }

  handleClick(type) {
    this.setState({ trips: type });
  }

  render() {
    return (
      <div align="center">
        <GameBoard
          trips={this.state.trips}
          onClick={i => this.handleClick(i)}
        />
      </div>
    );
  }
}


ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />

也许还有更多,比如明智地选择变量名。此外,您不需要像那样传递您的整个状态 (game: this.state)。只需传递您需要的道具。即trips: this.state.trips

【讨论】: