这是我第一次尝试 React TypeScript,并没有完全理解我在尝试构建可重用 Input 组件时遇到的错误。接近这种组件的 TypeScript 方式是什么?
请参阅下面的组件和错误:
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;
错误
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 |
我认为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;
或者,您可以将Input
和合二为一,FormInput
让 TypeScript 为您推断:
const FormInput = React.forwardRef<HTMLInputElement, InputProps>(({ name, label, ...otherProps }, ref) => {
...
});
export default FormInput;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句