将forwardRef与React一起使用.FC组件



我正在尝试将forwardRef与React一起使用。Typescript中的FC组件,但我得到以下TS错误:

const Input: React.FC<InputProps>
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'.

这是我的代码:

import React, { forwardRef } from 'react';
import style from './CustomInput.module.css';
interface InputProps {
value: string;
onChange: (value: string) => void;
onClick: () => void;
}
const Input: React.FC<InputProps> = ({ value, onClick, onChange }, ref) => {
return (
<input
className={style.CustomInput}
type="text"
value={value}
ref={ref}
onChange={e => onChange(e.target.value)}
onClick={onClick}
/>
);
};
export default forwardRef(Input);

我试着为裁判提供这样的额外道具:React.FC = ({ value, onClick, onChange }: InputProps, ref: HTMLInputElement)

但这似乎并不能解决问题,有什么想法可以解决这个TS错误吗?

如果您不需要React.FC,请不要使用它。

function Input({value, onClick, onChange}: InputProps, ref) {
return (
<input
className={style.CustomInput}
type="text"
value={value}
ref={ref}
onChange={e => onChange(e.target.value)}
onClick={onClick}
/>
);
});

export default forwardRef(Input);

最新更新