interface Props<T extends FieldValues> {
label: string;
id: keyof T;
type?: string;
register: UseFormRegister<T>;
error?: string;
}
const FormField = <T extends FieldValues>({
label,
id,
type = 'text',
register,
error,
}: Props<T>) => {
return (
<div className='flex flex-col gap-4 border p-2'>
<label className='font-bold' htmlFor={id as string}>
{label}
</label>
<input type={type} id={id as string} {...register(id as Path<T>)} />
{error && <span className='text-red-500'>{error}</span>}
</div>
);
};
export default FormField;
但我觉得这不是正确的方法,或者也许现在我不知道。如果有人构建了类似的组件,我将不胜感激帮助和建议
className
、
placeholder
、
disabled
等,以进一步自定义输入并尝试添加其他样式或辅助功能使错误对用户来说更加明显,例如更改输入边框颜色或添加
aria
角色。您还可以添加注释来解释每个道具及其用途以及如何使用该组件的示例。
import { FieldValues, UseFormRegister, Path } from 'react-hook-form';
// define props interface for the FormField component
interface Props<T extends FieldValues> {
label: string; // label for the input field
id: keyof T; // unique identifier for the input field
type?: string; // type of the input field (default is 'text')
register: UseFormRegister<T>; // function provided by react-hook-form for registering the input field
error?: string; // error message to display (optional)
className?: string; // additional css class name for styling (optional)
placeholder?: string; // placeholder text for the input field (optional)
disabled?: boolean; // flag to disable the input field (optional)
}
// define the FormField component
const FormField = <T extends FieldValues>({
label,
id,
type = 'text',
register,
error,
className,
placeholder,
disabled,
}: Props<T>) => {
return (
<div className={`flex flex-col gap-4 border p-2 ${className}`}>
{/* Label for the input field */}
<label className='font-bold' htmlFor={id as string}>
{label}
</label>
{/* Input field */}
<input
type={type} // Input type
id={id as string} // Unique identifier
{...register(id as Path<T>)} // Register the input field with react-hook-form
placeholder={placeholder} // Placeholder text (if provided)
disabled={disabled} // Disable the input field (if specified)
className={`border rounded p-2 ${error ? 'border-red-500' : ''}`} // CSS classes for styling
/>
{/* Display error message (if provided) */}
{error && <span className='text-red-500'>{error}</span>}
</div>
);
};
export default FormField;