繁体   English   中英

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

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

我已经使用 Material UI 5 配置了一个 Autocomplete 和一个 DatePicker 组件。

如何添加反应钩子形式支持? 我的自动完成标签如下所示:

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

附加的代码框示例与 react-hook-form V6 以非常相似的方式工作。

但是使用 React hook form V7 我的默认值没有得到验证:

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

首先,在您的代码中:

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

register()从不返回itemsIdFormHookReffromFormHookRef属性,但它返回一个ref所以你的意思可能是这样的:

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

如果您希望react-hook-form验证您的默认值,则需要在调用useForm时将这些值传递给defaultValues属性,而不是将您的initialState保存在单独的变量中:

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

现场演示

编辑 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