【问题标题】:Getting value of checked radio button using Material UI Radio使用 Material UI Radio 获取选中单选按钮的值
【发布时间】:2019-10-31 10:31:01
【问题描述】:

我正在创建一个表单,现在尝试进行一些输入验证,并且我正在努力从我的无线电组件中获取选中的值。

在我的一个文件中:

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

【问题讨论】:

    标签: reactjs radio-button material-ui radio-group


    【解决方案1】:

    它看起来更简单

    document.querySelector('[name="method-of-payment"]:checked')
    

    【讨论】:

      【解决方案2】:

      这看起来很可能是一种容易出错的方法,并且通常直接访问元素是一种 React 反模式。

      更好的方法是将选中的&lt;Radio&gt; 元素值作为属性存储在您的状态中。使用您的&lt;RadioGroup&gt;onChange 属性来挂钩选择何时更改,将其存储在您的状态中并在包含&lt;RadioGroup&gt;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>
          );
        }
      }
      

      Codepen here

      【讨论】:

      • 非常感谢您的回复!这看起来与我的代码实际上几乎相同,我可能应该展示所有内容。问题是找到一种从另一个文件中获取当前状态值的方法,该文件执行验证。
      猜你喜欢
      • 2020-07-06
      • 2019-12-08
      • 1970-01-01
      • 2017-01-20
      • 2019-05-11
      • 2017-04-05
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多