我正在尝试通过选中单选按钮来更改状态。当我检查它时,它仅在我检查下一个单选按钮后才更新该值。如果单击第一个单选按钮,则不会更改状态;如果单击第二个单选按钮,它将使用先前检查的单选按钮的值更新状态。谁能帮我解决这个问题?
class App extends React.Component {
state = { checked: false, radioValue: '' }
handleChange = (event) => {
const target = event.target;
const value = target.value;
const name = target.name;
console.log("this.state", this.state); // Gets previous value
this.setState({
[name]: value
});
}
render() {
return (
<div className="wrapper">
<input
name="radioValue"
type="radio"
value="aaa"
checked={this.state.radioValue === 'aaa'}
onChange={this.handleChange} />First Radio Button
<br />
<input
name="radioValue"
type="radio"
value="bbb"
checked={this.state.radioValue === 'bbb'}
onChange={this.handleChange} />Second Radio Button
</div>
);
}
}
export default App;
答案 0 :(得分:0)
this.setState({
[name]: value
},()=>console.log(this.state));
您还可以通过在setstate中使用回调来进行类似的检查
答案 1 :(得分:0)
请尝试这个。 App类扩展了React.Component {
constructor(props) {
super(props);
this.state = {
checked: ""
};
}
handleChange = (event) => {
console.log("this.state", this.state); // Gets previous value
this.setState({
checked: event.target.value
});
}
render() {
return (
<div className="wrapper">
<input name="radioValue" type="radio" value="aaa"
checked={this.state.checked === 'aaa'}
onChange={this.handleChange} />
First Radio Button
<br />
<input name="radioValue" type="radio" value="bbb"
checked={this.state.checked === 'bbb'}
onChange={this.handleChange} />
Second Radio Button
</div>
);
}
}
在我的机器上效果很好。