【问题标题】:How is Material UI's React rating component used in a form?Material UI 的 React 评分组件是如何在表单中使用的?
【发布时间】:2020-11-22 03:12:38
【问题描述】:

我正在尝试在 react-hook-form 中使用 Material UI 的 React 评级组件。

  ... 
  <form onSubmit={handleSubmit(onSubmit)}>
      <FormControlLabel
        control={
          <Checkbox
            inputRef={register}
            name="remember"
            defaultValue={false}
          />
        }
        label="remember"
      />
      <br />
      <FormControlLabel
        control={
          <Rating
            inputRef={register}
            name="rating"
            defaultValue={2}
            precision={1}
            icon={<RadioButtonUncheckedIcon fontSize="inherit" />}
          />
        }
        label="select rating"
      />
      <Button type="submit">
        Submit
      </Button>
    </form>
    ...

我不明白为什么评级组件的值没有被注册,但复选框的值是。请在https://codesandbox.io/s/suspicious-drake-1d0kx?file=/src/form.js 找到代码(提交时,评分的值不会打印到控制台,而复选框的值是)。

【问题讨论】:

    标签: reactjs forms material-ui frontend


    【解决方案1】:

    根据docRating 没有input 元素可以将ref 传递给喜欢TextFieldCheckbox,因此解决方案是创建一个隐藏的输入替换来存储评分值

    <FormControlLabel
      control={
        <>
          <input
            name="rating"
            type="number"
            value={rating}
            ref={register}
            hidden
            readOnly
          />
          <Rating
            name="rating"
            value={rating}
            precision={1}
            onChange={(_, value) => {
              setRating(value);
            }}
            icon={<RadioButtonUncheckedIcon fontSize="inherit" />}
          />
        </>
      }
      label="select rating"
    />
    

    下面是修改的分叉代码框链接

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 2020-11-23
      • 2020-11-18
      • 2019-04-26
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多