简体   繁体   English

react-hook-form 和 material-ui FormControl

[英]react-hook-form and material-ui FormControl

So I am trying to register some radio buttons for my form, however it will not register.所以我试图为我的表单注册一些单选按钮,但它不会注册。

<FormControl component="fieldset" inputRef={register({ required: true })}>
  <FormLabel component="legend">Promoting</FormLabel>
  <RadioGroup aria-label="promoting" name="promoting" value={promoting} onChange={handleChange} inputRef={register({ required: true })}>
    <FormControlLabel value="business" control={<Radio  />} label="Business" />
    <FormControlLabel value="nonprofit" control={<Radio />} label="Non-Profit" />
    <FormControlLabel value="event" control={<Radio  />} label="Event" />
  </RadioGroup>
</FormControl>

I am wondering what I am doing wrong我想知道我做错了什么

Full code完整代码

export default function BuildAd() {
  const [promoting, setValue] = React.useState('female');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const { register, handleSubmit, errors } = useForm();

  const onSubmit = data => console.log(data);
  console.log(errors);
  
  return (
    <div style={{ padding: 16, margin: 'auto', maxWidth: 600 }}>
    <CssBaseline />
    
    <Typography variant="h5" align="center" component="h2" gutterBottom>
      Create your campaign
    </Typography>
         <Paper style={{ padding: 16 }}>
              <form onSubmit={handleSubmit(onSubmit)}>
                <input type="text" placeholder="First name" name="First name" ref={register({required: true, maxLength: 80})} />
                <input type="text" placeholder="Last name" name="Last name" ref={register({required: true, maxLength: 100})} />
                <input type="text" placeholder="Email" name="Email" ref={register({required: true, pattern: /^\S+@\S+$/i})} />
                <input type="tel" placeholder="Mobile number" name="Mobile number" ref={register({required: true, minLength: 6, maxLength: 12})} />
                <select name="Title" ref={register({ required: true })}>
                  <option value="Mr">Mr</option>
                  <option value="Mrs">Mrs</option>
                  <option value="Miss">Miss</option>
                  <option value="Dr">Dr</option>
                </select>

                <input name="Developer" type="radio" value="Yes" ref={register({ required: true })}/>
                <input name="Developer" type="radio" value="No" ref={register({ required: true })}/>


                <Typography variant="h5">What are you Advertising</Typography>
                    <Box m={2}/>
                    <FormControl component="fieldset" inputRef={register({ required: true })}>
                    <FormLabel component="legend">Promoting</FormLabel>
                    <RadioGroup aria-label="promoting" name="promoting" value={promoting} onChange={handleChange} inputRef={register({ required: true })}>
                      <FormControlLabel value="business" control={<Radio inputRef={register({ required: true })} />} label="Business" />
                      <FormControlLabel value="nonprofit" control={<Radio inputRef={register({ required: true })} />} label="Non-Profit" />
                      <FormControlLabel value="event" control={<Radio inputRef={register({ required: true })} />} label="Event" />
                    </RadioGroup>
                  </FormControl>
                  
                <input type="submit" />
            </form>
      </Paper>
    </div>
  );
}

You can fallback on controllable components by using Controller if it doesn't work.如果Controller不起作用,您可以使用Controller回退可控组件。

In your case, I suspect it's because the name props passed to your <RadioGroup /> is not the same as the name attribute when passed into native input like <input /> or <select /> .在您的情况下,我怀疑这是因为传递给您的<RadioGroup />name道具传递到本机输入(如<input /><select />时的name属性不同。

const { register, handleSubmit, errors, control } = useForm();
const onSubmit = (data) => alert(JSON.stringify(data, null, 2));
<form onSubmit={handleSubmit(onSubmit)}>
  <FormControl component="fieldset">
    <FormLabel component="legend">Promoting</FormLabel>
    <Controller
      rules={{ required: true }}
      control={control}
      defaultValue="business"
      name="promoting"
      as={
        <RadioGroup>
          <FormControlLabel
            value="business"
            control={<Radio />}
            label="Business"
          />
          <FormControlLabel
            value="nonprofit"
            control={<Radio />}
            label="Non-Profit"
          />
          <FormControlLabel
            value="event"
            control={<Radio />}
            label="Event"
          />
        </RadioGroup>
      }
    />
  </FormControl>

  <input type="submit" />
</form>

If you want to read the value when onChange fires, you cannot do that when passing the element to the as props:如果您想在onChange触发时读取值,则在将元素传递给as props 时不能这样做:

<Controller
  {...}
  as={
    <MyComponent
      onChange={handleChange} // handleChange will never be called
    />
  }
/>

The reason is because Controller will copy the element that you pass in and pass its own onChange props that will override yours.原因是因为Controller将复制您传入的元素并传递其自己的onChange道具,这些道具将覆盖您的。 See here and here .请参阅此处此处

To fix that problem, you need to use another way to pass the element down by using render props to gain more control on how you should render your components.为了解决这个问题,你需要使用另一种方式通过使用render道具来传递元素,以更好地控制你应该如何渲染你的组件。

<Controller
  rules={{ required: true }}
  control={control}
  defaultValue="business"
  name="promoting2"
  render={({ name, onBlur, onChange, value }) => (
    <RadioGroup
      value={value}
      onBlur={onBlur}
      onChange={(e) => {
        onChange(e);
        console.log(e.target.value); // will be called this time
      }}
    >
      <FormControlLabel
        value="business"
        control={<Radio />}
        label="Business"
      />
      {...}
    </RadioGroup>
  )}
/>

Live Demo现场演示

编辑 64042394/react-hook-form-and-material-ui-formcontrol

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 react-hook-form 和 Material-UI 解决问题 - React problem with react-hook-form and Material-UI react-hook-form material-ui 表单只提交一次作品 - react-hook-form material-ui Form submit works only once React-hook-form with Material-ui textfield without autoFocus defaultValue 在表单提交过程中消失了 - React-hook-form with Material-ui textfield without autoFocus defaultValue disappeared during form submit React - Material-UI - 如何在 react-hook-form 中使用 Select 和多个值 - React - Material-UI - How to use Select with multiple values inside react-hook-form 使用<TextField />带有 react-hook-form 的 material-ui 组件显示警告 - Using <TextField /> component from material-ui with react-hook-form shows warning 使用 react-hook-form 重置功能时,Material-UI 复选框不会重置 - Material-UI Checkbox is not reset while using react-hook-form reset function 使用 material-ui 进行 react-hook-form 验证 - 未插入第一个击键 - react-hook-form validation with material-ui - first keystroke not inserted 使用带有日期/时间选择器的 react-hook-form 并使用 Material-UI 的示例? - Example of using react-hook-form with a Date/Time Picker and using Material-UI? 带有 material-ui 的 React-hook-form 不会在 onBlur() 方法中保持值变化 - React-hook-form with material-ui does not keep value change in onBlur() method 带有 material-ui 的 React-hook-form 不显示来自规则的错误 - React-hook-form with material-ui does not show errors from rules
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM