import React, { useRef } from 'react';
import { useFormContext, Controller, type UseFormReturn } from 'react-hook-form';
import {
Box,
Typography,
TextField,
FormControl,
InputLabel,
Select,
MenuItem,
Grid,
Avatar,
Button,
IconButton,
} from '@mui/material';
import {
PhotoCamera as PhotoCameraIcon,
Delete as DeleteIcon,
} from '@mui/icons-material';
interface GeneralFormProps {
form?: UseFormReturn;
onSubmit?: (data: any) => void;
isSubmitting?: boolean;
onCancel?: () => void;
submitButtonText?: string;
cancelButtonText?: string;
}
function GeneralForm({
form: propForm,
onSubmit,
isSubmitting,
onCancel,
submitButtonText = '保存',
cancelButtonText = '取消',
}: GeneralFormProps = {}) {
// 优先使用props传递的form,否则使用FormProvider的context
let contextForm: UseFormReturn | null = null;
try {
contextForm = useFormContext();
} catch (error) {
contextForm = null;
}
const form = propForm || contextForm;
if (!form) {
console.error('GeneralForm: No form context found. Component must be used within a FormProvider or receive a form prop.');
return (
表单配置错误:请确保组件在FormProvider中使用或传递form参数
);
}
const { control, watch, setValue, handleSubmit } = form;
const fileInputRef = useRef(null);
const handleAvatarUpload = (event: React.ChangeEvent) => {
const file = event.target.files?.[0];
if (file && form) {
const reader = new FileReader();
reader.onload = (e) => {
form.setValue('avatar', e.target?.result as string);
};
reader.readAsDataURL(file);
}
};
const handleAvatarDelete = () => {
if (form) {
form.setValue('avatar', undefined);
}
};
const handleAvatarClick = () => {
fileInputRef.current?.click();
};
const avatar = watch('avatar', '');
return (
基础信息
{!avatar && }
}
onClick={handleAvatarClick}
>
上传头像
{avatar && (
)}
{/* 表单字段 */}
(
)}
/>
(
)}
/>
(
权限设置
)}
/>
{/* 表单操作按钮 - 仅在有onSubmit回调时显示 */}
{onSubmit && (
{onCancel && (
)}
)}
);
}
export default GeneralForm;