简体   繁体   English

React Hook Form V7 + Material UI 5:默认值未验证

[英]React Hook Form V7 + Material UI 5: Default values not validated

I have configured an Autocomplete and a DatePicker component using Material UI 5.我已经使用 Material UI 5 配置了一个 Autocomplete 和一个 DatePicker 组件。

How to add react hook form support?如何添加反应钩子形式支持? My AutoComplete tag looks like this:我的自动完成标签如下所示:

const { itemsIdFormHookRef, ...itemsIdFormHookRest } = register("itemsId", {
    required: true
});

<Autocomplete
    options={state.itemsList}
    getOptionLabel={(item) => (item.name ? item.name : "")}
    getOptionSelected={(option, value) =>
      value === undefined || value === "" || option.id === value.id
    }
    value={
      state.itemIdSelected
        ? state.itemsList.find(
            (item) => item.id === state.itemIdSelected
          )
        : ""
    }
    onChange={(event, items) => {
      if (items !== null) {
        dispatch({
          type: SET_ITEM_ID,
          payload: items.id
        });
      }
    }}
    renderInput={(params) => (
      <TextField
        {...params}
        {...itemsIdFormHookRest}
        label="items"
        margin="normal"
        variant="outlined"
        inputRef={itemsIdFormHookRef}
        error={errors.itemsId ? true : false}
        helperText={errors.itemsId && "item required"}
        required
      />
    )}
  />

The attached codesandbox example was working in very similar fashion with react-hook-form V6.附加的代码框示例与 react-hook-form V6 以非常相似的方式工作。

But with react hook form V7 my default values are not validated:但是使用 React hook form V7 我的默认值没有得到验证:

https://codesandbox.io/s/react-hook-form-v7-material-ui-5-hz7j6 https://codesandbox.io/s/react-hook-form-v7-material-ui-5-hz7j6

First off, in your code here:首先,在您的代码中:

const { itemsIdFormHookRef, ...itemsIdFormHookRest } = register(...);
const { fromFormHookRef, ...fromFormHookRest } = register(...);

register() never returns itemsIdFormHookRef or fromFormHookRef property but it returns a ref so maybe what you mean is this: register()从不返回itemsIdFormHookReffromFormHookRef属性,但它返回一个ref所以你的意思可能是这样的:

const { ref: itemsIdFormHookRef, ...itemsIdFormHookRest } = register(...);
const { ref: fromFormHookRef, ...fromFormHookRest } = register(...);

If you want react-hook-form to validate your default value, you need to pass those values to the defaultValues property when calling useForm instead of keeping your initialState in a separate variable:如果您希望react-hook-form验证您的默认值,则需要在调用useForm时将这些值传递给defaultValues属性,而不是将您的initialState保存在单独的变量中:

const {...} = useForm({
  defaultValues: {
    itemsId: 1,
    fromDate: new Date()
  }
});

Live Demo现场演示

编辑 67068456/react-hook-form-v7-material-ui-5-default-values-not-validated

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM