[英]How to create a reusable Input component with React & TypeScript?
It's my first attempt with React TypeScript and don't fully understand the error I'm getting when trying to build a reusable Input component.这是我第一次尝试使用 React TypeScript 并且不完全理解我在尝试构建可重用输入组件时遇到的错误。 What is the TypeScript way of approaching this kind of component? TypeScript 接近这种元件的方法是什么?
See Component & Error below:请参阅下面的组件和错误:
import React, { FC, InputHTMLAttributes } from 'react'; interface InputProps extends InputHTMLAttributes<HTMLInputElement> { name: string; label: string; ref: string; } const Input: FC<InputProps> = ({ name, label, ...otherProps }, ref) => { return ( <label className={styles.formLabel}> {label} <input className={styles.formInput} {...otherProps} name={name} ref={ref} /> </label> ); }; const FormInput = React.forwardRef(Input); export default FormInput;
Error错误
TypeScript error in /Users/Timmchoover/Documents/Projects/evaly/evaly-app/src/before-login/components/forms/form-input/form-input.component.tsx(25,36): Argument of type 'FC<InputProps>' is not assignable to parameter of type 'ForwardRefRenderFunction<unknown, InputProps>'. Types of property 'defaultProps' are incompatible. Type 'Partial<InputProps> | undefined' is not assignable to type 'undefined'. Type 'Partial<InputProps>' is not assignable to type 'undefined'. TS2345 23 | }; 24 | > 25 | const FormInput = React.forwardRef(Input); | ^ 26 | 27 | export default FormInput; 28 |
I don't think FC
is satisfying the type constraint here, try ForwardRefRenderFunction
instead:我不认为FC
在这里满足类型约束,请尝试ForwardRefRenderFunction
代替:
import React, { ForwardRefRenderFunction, InputHTMLAttributes } from 'react';
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
name: string;
label: string;
ref: string;
}
const Input: ForwardRefRenderFunction<HTMLInputElement, InputProps> = ({ name, label, ...otherProps }, ref) => {
return (
<label className={styles.formLabel}>
{label}
<input
className={styles.formInput}
{...otherProps}
name={name}
ref={ref}
/>
</label>
);
};
const FormInput = React.forwardRef(Input);
export default FormInput;
Alternatively, you can combine Input
and FormInput
into one and let TypeScript infer for you:或者,您可以将Input
和FormInput
,让 TypeScript 为您推断:
const FormInput = React.forwardRef<HTMLInputElement, InputProps>(({ name, label, ...otherProps }, ref) => {
...
});
export default FormInput;
const Input = ({ name, label, ...otherProps }, ref) => {
return (
<label className={styles.formLabel}>
{label}
<input
className={styles.formInput}
{...otherProps}
name={name}
ref={ref}
/>
</label>
);
};
**just remove the **:FC **只需删除 **:FC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.