javascript - 为什么单选按钮没有被选中?

标签 javascript html reactjs radio-button checked

我有

<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/

相关文章:

javascript - tf.compat.v1.image.resize 的等效 tensorflow.js 函数?

javascript - 如何使用 Protractor 和 Chrome 浏览器打开新标签页

javascript - 在另一个 div 中附加一个 HTML div

reactjs - 使用 ReactJS 将插件添加到 CKEditor5 的自定义构建中

javascript - 使用 ontouchmove 只触发一次

html - 使用 float 垂直对齐底部 img 和文本

javascript - 我可以为此添加鼠标悬停声音吗?

html - 溢出-y :hidden and overflow-x:hidden but how do I scroll down without the scroll bar

reactjs - 确保类型 A 扩展了类型 B,它有一个字段是另一个对象的值

ios - React Native rnpm unlink 库