简体   繁体   English

为什么不选中单选按钮?

[英]Why radiobutton isn't checked?

I have 我有

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

When I reload page radiobutton is checked as it should, but when I try to check another I can't select anything (dot in radiobutton disappears) But when I click save it saves right !!! 当我重新加载页面单选按钮时,它应该被检查,但是当我尝试检查另一个按钮时,我什么也无法选择(单选按钮中的点消失了),但是当我单击“保存”时,它可以正确保存! (value of the last radiobutton pressed). (最后按下的单选按钮的值)。 I can't understand.. Maybe someone knows what's wrong ? 我听不懂。也许有人知道怎么了?

you should have state for rendering your html with new values. 您应该具有使用新值呈现html的状态。 set your initial state like this (if you're using es6): 像这样设置您的初始状态(如果您使用的是es6):

constructor (props) {
 super(props)
 this.state = {
  is_active: this.props.is_active
 }
}

also you will need a function to call on button's click, which will change the state: 您还需要一个函数来调用按钮的单击,这将更改状态:

setCheckedValue (val) {
 this.setState({is_active: val})
}

and finally your html will look like this: 最后,您的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

You have to add a onClick event to change the value of is_active. 您必须添加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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM