我有以下具有两个单选按钮的react组件。
export default class DemoApp extends Component {
constructor(props) {
super(props);
this.onThemeChange = ::this.onThemeChange;
this.state = {
theme: "dark"
};
}
onThemeChange(e) {
this.setState({
theme: e.target.value
});
}
render() {
return (
<Fragment>
<div className="radio">
<label htmlFor="light-theme">
<input
type="radio"
value="light"
onChange={this.onThemeChange}
checked={this.state.theme === "light"}
name="theme"
id="light-theme"
/>
light
</label>
</div>
<div className="radio">
<label htmlFor="dark-theme">
<input
type="radio"
value="dark"
name="theme"
checked={this.state.theme === "dark"}
onChange={this.onThemeChange}
id="dark-theme"
/>
Dark
</label>
</div>
</Fragment>
);
}
}
单选按钮功能正常。但是他们得到了检查,即只有默认的一个被检查了,即使状态值更改了也保持选中状态。我也尝试了defaultChecked属性,但没有运气。
<div className="radio">
<label htmlFor="dark-theme">
<input
type="radio"
value="dark"
name="theme"
checked={this.state.theme === "dark"}
onChange={this.onThemeChange}
id="dark-theme"
/>
Dark
</label>
</div>
有人可以帮助我找出我在做什么错吗?