为什么没有选中单选按钮?

Why radiobutton isn't 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>

当我重新加载页面时,radiobutton 被选中,但当我尝试检查另一个时,我不能 select 任何东西(radiobutton 中的点消失) 但是当我点击保存时它保存正确! (最后按下的单选按钮的值)。 我无法理解.. 也许有人知道出了什么问题?

您必须添加一个 onClick 事件才能更改 is_active 的值。

<label><input type='radio' name='is_active' value='true' checked={this.props.is_active==true ? true : false} onClick={this.props.is_active=true} /> Active</label>
<label><input type='radio' name='is_active' value='false' checked={this.props.is_active==false ? true : false} onClick={this.props.is_active=false} /> Passive</label>                                                    
<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