gpt4 book ai didi

javascript - 状态正在更新但未显示

转载 作者:行者123 更新时间:2023-12-02 22:37:19 26 4
gpt4 key购买 nike

我有一个文本框,一个可单击按钮和另一个不可单击按钮,我用它在按下可单击按钮时显示数字,我希望文本框中的值显示在另一个按钮中。 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;

最佳答案

您应该再次阅读文档。不要像在 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)。只需传递您需要的 Prop 即可。即,行程:this.state.trips

关于javascript - 状态正在更新但未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58703124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com