feat(form): add form field components and configuration updates
refactor(knowledge): restructure configuration components to use common items
This commit is contained in:
72
src/components/FormField/SwitchFormField.tsx
Normal file
72
src/components/FormField/SwitchFormField.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
FormControlLabel,
|
||||
Switch,
|
||||
FormHelperText,
|
||||
} from '@mui/material';
|
||||
import { Controller, useFormContext } from 'react-hook-form';
|
||||
|
||||
export interface SwitchFormFieldProps {
|
||||
name: string;
|
||||
label: string;
|
||||
helperText?: string;
|
||||
defaultValue?: boolean;
|
||||
disabled?: boolean;
|
||||
required?: boolean;
|
||||
size?: 'small' | 'medium';
|
||||
color?: 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning';
|
||||
}
|
||||
|
||||
export const SwitchFormField: React.FC<SwitchFormFieldProps> = ({
|
||||
name,
|
||||
label,
|
||||
helperText,
|
||||
defaultValue = false,
|
||||
disabled = false,
|
||||
required = false,
|
||||
size = 'medium',
|
||||
color = 'primary',
|
||||
}) => {
|
||||
const { control } = useFormContext();
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Controller
|
||||
name={name}
|
||||
control={control}
|
||||
defaultValue={defaultValue}
|
||||
rules={{
|
||||
required: required ? `${label}是必填项` : false,
|
||||
}}
|
||||
render={({ field, fieldState: { error } }) => (
|
||||
<>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={field.value || false}
|
||||
onChange={field.onChange}
|
||||
disabled={disabled}
|
||||
size={size}
|
||||
color={color}
|
||||
/>
|
||||
}
|
||||
label={
|
||||
<Typography variant="body1">
|
||||
{required && <span style={{ color: 'red' }}>*</span>}
|
||||
{label}
|
||||
</Typography>
|
||||
}
|
||||
/>
|
||||
{(error || helperText) && (
|
||||
<FormHelperText error={!!error}>
|
||||
{error?.message || helperText}
|
||||
</FormHelperText>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user