我正在尝试创建一个yes-no单选按钮,但只有只使用一个状态。因此,我有这样的事情:
<label className="radio-inline">
<input
type="radio"
name={this.props.nameYes}
defaultChecked={this.props.state}
onChange={this.props.onChangeEmailNotifications}
value="yes"/>Yes
</label>
<label className="radio-inline">
<input
type="radio"
name={this.props.nameNo}
defaultChecked={!this.props.state}
onChange={this.props.onChangeEmailNotifications}
value="no"/>No
</label>
我通过父组件传递的状态设置为true。
这个onChange函数是:
changeCheckboxState: function(event){
var chcName = event.target.name;
switch(chcName){
case "chcEmailNotificationsYes":
this.state.user.emailNotifications = event.target.checked;
this.setState({user: this.state.user});
console.log('checkbox ' + chcName + " state je : ", this.state.user.emailNotifications);
break;
case "chcEmailNotificationsNo":
this.state.user.emailNotifications = !event.target.checked;
this.setState({user: this.state.user});
console.log('checkbox ' + chcName + " state je : ", this.state.user.emailNotifications);
break;
default:
console.log("Sad smo u default");
}
}
但那些单选按钮不起作用。在控制台日志中,我看到状态已更改,但它对单选按钮没有影响。
有没有办法在开始时将状态设置为null,不检查按钮?
答案 0 :(得分:1)
使用checked
代替defaultChecked
作为输入广播道具
答案 1 :(得分:0)
我认为您的单选按钮未被检查,因为React期待点击事件(请参阅https://facebook.github.io/react/docs/forms.html#potential-issues-with-checkboxes-and-radio-buttons),根据该链接,您需要删除对preventDefault的调用。您的语法对我来说也不正确 -
这是道具状态(如果这是正确的我建议使用不同的属性名称)
defaultChecked={this.props.state}
看起来应该是这样的
defaultChecked={this.state.xxxx}
关于状态设置,您可以使用getInitialState
将状态设置为null
,然后可以更新onChange
或使用点击方式。
您对defaultChecked
的使用似乎是正确的。