如何使用 React 只选择一个单选按钮 [英] How to keep only one radio button selected with React
问题描述
我正在尝试通过用它做一个小应用程序来学习 React.我的应用程序有两个单选按钮,我想始终只选中其中一个,但是当我选择另一个按钮时,似乎无法弄清楚如何取消选中另一个按钮.相反,他们都保持选中状态.这是它的 jsfiddle:
https://jsfiddle.net/4us5us2o/
这是代码:
var MyRadioButton = React.createClass({handleChange:函数(){this.props.onChange(this.props.myValue)},渲染:函数(){返回 (<input type="radio" onChange={this.handleChange}>{this.props.myValue}</input>)}});var MyApp = React.createClass({getInitialState: 函数 () {返回 {选定值:''}},更改值:函数(新值){this.setState({selectedValue: newValue })},渲染:函数(){返回 (<div><MyRadioButton onChange={this.changeValue} myValue="A"/><MyRadioButton onChange={this.changeValue} myValue="B"/><br></br>
)}});
您需要在输入元素上提供名称属性,以将它们标记为同一单选按钮组的一部分. 元素的这种标准行为输入收音机.
在您的示例中,您可以使用:
{this.props.myValue}</input>
Im trying to learn React by doing a small application with it. My application has two radio buttons and I would like to keep always only one of them checked, but cannot seem to figure out how to uncheck the other button when I select the other one. Instead they both remain selected. Here is a jsfiddle for it:
https://jsfiddle.net/4us5us2o/
And here is the code:
var MyRadioButton = React.createClass({
handleChange: function () {
this.props.onChange(this.props.myValue)
},
render: function () {
return (
<input type="radio" onChange={this.handleChange}>{this.props.myValue}</input>
)
}
});
var MyApp = React.createClass({
getInitialState: function () {
return {
selectedValue: ''
}
},
changeValue: function (newValue) {
this.setState({selectedValue: newValue })
},
render: function () {
return (
<div>
<MyRadioButton onChange={this.changeValue} myValue="A" />
<MyRadioButton onChange={this.changeValue} myValue="B" /><br></br>
</div>
)
}
});
You need to provide a name attribute on your input elements to mark them as part of the same radio button group. This standard behavior for an <input> element with type radio.
In your example, you could use:
<input type="radio" name="myGroupName" onChange={this.handleChange}>{this.props.myValue}</input>
这篇关于如何使用 React 只选择一个单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!