反应钩子形式的可重用自定义组件

问题描述 投票:0回答:1
所以我一直在尝试制作一个可重用的输入组件,这样我就不必在任何地方复制粘贴所有样式,我做了这个 从 'react-hook-form' 导入 { FieldValues, UseFormRegister, Path };

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;
但我觉得这不是正确的方法,或者也许现在我不知道。如果有人构建了类似的组件,我将不胜感激帮助和建议

reactjs typescript react-hook-form
1个回答
0
投票
您应该尝试通过接受可以传播到输入元素上的其他道具来增加更多灵活性,例如

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;
    
© www.soinside.com 2019 - 2024. All rights reserved.