状态正在更新,但未显示

问题描述 投票:0回答:1

我有一个文本框,一个可单击的按钮,另一个非可单击的按钮,当单击可单击的按钮时,我用来显示数字。我希望文本框中的值显示在另一个按钮中。 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;
javascript reactjs
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.