简体   繁体   中英

got 'DatePickerProps<unknown>': onChange, value, renderInput' when trying to create custom component with MUI and react-hook-form

I'm trying to make reusable component out of MUI Datepicker and React Hook Form

but got Type '{ control: Control<FieldValues, object>; name: string; }' is missing the following properties from type 'DatePickerProps<unknown>': onChange, value, renderInput ts(2739) Type '{ control: Control<FieldValues, object>; name: string; }' is missing the following properties from type 'DatePickerProps<unknown>': onChange, value, renderInput ts(2739) Type '{ control: Control<FieldValues, object>; name: string; }' is missing the following properties from type 'DatePickerProps<unknown>': onChange, value, renderInput ts(2739) on the parent component

I'm getting stuck now:

import { DatePickerProps } from "@mui/lab";
import { ComponentProps } from "react";

import { Control, Controller } from "react-hook-form";

import DateInputComponent from "./DateInputComponent";

type Props = {
  name: string;
  control: Control;
  errors?: {
    [x: string]: any;
  };
  rules?: any;
  defaultValue?: any;
} & ComponentProps<typeof DateInputComponent>;

type ExtendedProps = Props & DatePickerProps;

const ControlledDateInput = ({
  name,
  control,
  errors,
  rules,
  defaultValue,
  ...props
}: ExtendedProps) => {
  return (
    <Controller
      control={control}
      name={name}
      rules={rules}
      defaultValue={defaultValue}
      render={({ field: { onChange, onBlur, value } }) => (
        <DateInputComponent
          {...props}
          onChange={onChange}
          onBlur={onBlur}
          value={value}
          error={!!errors?.[name]}
          helperText={
            errors?.[name] ? errors?.[name]?.message || "Invalid field" : ""
          }
        />
      )}
    />
  );
};

export default ControlledDateInput;

It's way better to go to this sandbox: https://codesandbox.io/s/affectionate-drake-5bjbl?file=/src/App.tsx

Please help!!!

The DatePickerProps type takes 2 generics. (At the time you posted your question, it only required one.) You need to invoke the type like DatePickerProps<unknown, unknown> or DatePickerProps<Date, Date> , etc.

In my case, DatePickerProps from @mui/lab didn't have a proper type declared. I imported it from @mui/x-date-pickers as I was using the x-date-pickers package to render to my custom component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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