我正在创建一个表单,现在正在尝试执行一些输入验证,并且我正在努力从我的单选组件中获取检查值。
在一个文件中,我有:
<FormControl component="fieldset" name="method-of-payment">
<RadioGroup onChange={this.handleChange} >
<FormControlLabel value="credit" control={<Radio />} label="Credit Card"/>
<FormControlLabel value="check" control={<Radio />} label="Check"/>
<FormControlLabel value="purchase-order" control={<Radio />} label="Purchase Order"/>
</RadioGroup>
</FormControl>我正在尝试在另一个文件中获取值(它对其他所有文件都有效):
this.setState({
method-of-payment: document.getElementsByName('method-of-payment')[0].value
})但我没有运气得到正确的值。
我很感谢你的帮助。
编辑:这是我关注的文档的链接:https://material-ui.com/components/radio-buttons/
发布于 2019-06-18 04:00:31
这看起来很可能是一种容易出错的方法,而且通常直接访问元素是一种React反模式。
更好的方法是将选中的<Radio>元素值作为属性存储在您的州中。当选择更改时,使用<RadioGroup>的onChange属性来挂钩,将其存储在您的状态中,并在包含<RadioGroup>的value属性中使用此属性。
您应该添加一个事件侦听器,然后根据可以从事件中获得的value更新您的状态。如果你像这样把它挂起,那么你就不需要访问元素来找到它的值--你已经知道它在你所在的州了。
基本的例子是这样的:
class MyForm extends Component {
state = { selected: "credit" };
handleChange = ev => {
this.setState({ selected: ev.target.value });
};
render() {
const { selected } = this.state;
return (
<FormControl component="fieldset" name="method-of-payment">
<RadioGroup onChange={this.handleChange} value={selected}>
<FormControlLabel
value="credit"
control={<Radio />}
label="Credit Card"
/>
<FormControlLabel value="check" control={<Radio />} label="Check" />
<FormControlLabel
value="purchase-order"
control={<Radio />}
label="Purchase Order"
/>
</RadioGroup>
</FormControl>
);
}
}发布于 2020-10-17 04:27:27
它看起来更简单
document.querySelector('[name="method-of-payment"]:checked')https://stackoverflow.com/questions/56637932
复制相似问题