我有
<input type='radio' name='is_active' value='true' checked={this.props.is_active==true ? true : false}/> Active
<input type='radio' name='is_active' value='false' checked={this.props.is_active==false ? true : false}/> Passive
...
<button>Save</button>
当我重新加载页面单选按钮时,它应该被选中,但是当我尝试检查另一个单选按钮时,我无法选择任何内容(单选按钮中的点消失) 但是当我点击“保存”时,它保存正确! (最后按下的单选按钮的值)。 我无法理解.. 也许有人知道出了什么问题?
最佳答案
您应该具有使用新值渲染 html 的状态。 像这样设置你的初始状态(如果你使用的是 es6):
constructor (props) {
super(props)
this.state = {
is_active: this.props.is_active
}
}
您还需要一个函数来调用按钮的单击,这将改变状态:
setCheckedValue (val) {
this.setState({is_active: val})
}
最后你的 html 将如下所示:
<input type='radio' name='is_active' value='true' checked={this.state.is_active==true ? true : false} onClick={this.setCheckedValue.bind(this, 'true')}/> Active
<input type='radio' name='is_active' value='false' checked={this.state.is_active==false ? true : false} onClick={this.setCheckedValue.bind(this, 'false')}/> Passive
关于javascript - 为什么单选按钮没有被选中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41226447/