You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.4KB

  1. import { useFormContext, Controller } from "react-hook-form";
  2. import { TextField, TextFieldProps } from "@mui/material";
  3. import { useMemo } from "react";
  4. import { formatDateStr } from "utils/datetime";
  5. import TextFieldEx from "../form/TextFieldEx";
  6. // ----------------------------------------------------------------------
  7. type IProps = {
  8. name: string;
  9. readOnly?: boolean;
  10. };
  11. type Props = IProps & TextFieldProps;
  12. export type RHFTextFieldProps = Props;
  13. export default function RHFTextField({
  14. name,
  15. readOnly,
  16. size: fieldSize = "small",
  17. ...other
  18. }: Props) {
  19. const { control, watch } = useFormContext();
  20. const value = watch(name);
  21. const valueStr = useMemo(() => {
  22. if (typeof value === "string") {
  23. if (value === "") {
  24. return " ";
  25. } else {
  26. return value;
  27. }
  28. }
  29. if (value instanceof Date) {
  30. return formatDateStr(value);
  31. }
  32. if (readOnly) {
  33. return " ";
  34. }
  35. return "";
  36. }, [value]);
  37. if (readOnly) {
  38. return (
  39. <TextFieldEx readOnly {...other} value={valueStr} variant="standard" />
  40. );
  41. }
  42. return (
  43. <Controller
  44. name={name}
  45. control={control}
  46. render={({ field, fieldState: { error } }) => (
  47. <TextField
  48. {...field}
  49. fullWidth
  50. error={!!error}
  51. helperText={error?.message}
  52. {...other}
  53. size={fieldSize}
  54. />
  55. )}
  56. />
  57. );
  58. }