在TypeScript中使用forwardRef与React.FC组件遇TS错误求助
修复React+TypeScript中forwardRef与React.FC混用的TS错误
错误原因
React.FC类型的组件自带defaultProps属性(类型为Partial<InputProps> | undefined),但forwardRef接受的ForwardRefRenderFunction要求渲染函数的defaultProps必须是undefined,两者类型不兼容导致报错。
修复方案
方案一:移除React.FC类型声明,直接定义渲染函数
直接编写符合forwardRef要求的渲染函数,并显式指定ref的类型为ForwardedRef<HTMLInputElement>:
import React, { forwardRef, ForwardedRef } from 'react'; import style from './CustomInput.module.css'; interface InputProps { value: string; onChange: (value: string) => void; onClick: () => void; } const Input = ({ value, onClick, onChange }: InputProps, ref: ForwardedRef<HTMLInputElement>) => { return ( <input className={style.CustomInput} type="text" value={value} ref={ref} onChange={e => onChange(e.target.value)} onClick={onClick} /> ); }; export default forwardRef(Input);
方案二:显式指定渲染函数为ForwardRefRenderFunction类型
直接将渲染函数的类型声明为ForwardRefRenderFunction<HTMLInputElement, InputProps>,让TS严格匹配forwardRef的要求:
import React, { forwardRef, ForwardRefRenderFunction } from 'react'; import style from './CustomInput.module.css'; interface InputProps { value: string; onChange: (value: string) => void; onClick: () => void; } const Input: ForwardRefRenderFunction<HTMLInputElement, 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是为普通函数组件设计的类型,它的签名和forwardRef所需的渲染函数签名不匹配(前者带children和context参数,后者带ref参数),同时附带的defaultProps属性会和forwardRef的类型约束冲突,因此不要混用React.FC和forwardRef的渲染函数。
内容的提问来源于stack exchange,提问作者Alex T
相关产品推荐
相关产品推荐

