reactjs - React.forwardRef转发ref后如何定义Input组件ref的类型?
问题描述
代码
import React, { forwardRef, useRef } from "react";
import { Input } from "antd";
const Child = forwardRef<HTMLInputElement, any>((props, ref) => {
// typescript error
return <Input ref={ref} />;
});
const Parents = () => {
const inputRef = useRef<HTMLInputElement>(null);
return <Child ref={inputRef} />;
};
export default Parents
错误信息
TS2322: Type '((instance: HTMLInputElement) => void) | MutableRefObject<HTMLInputElement>' is not assignable to type 'LegacyRef<Input>'. Type '(instance: HTMLInputElement) => void' is not assignable to type 'LegacyRef<Input>'. Type '(instance: HTMLInputElement) => void' is not assignable to type '(instance: Input) => void'. Types of parameters 'instance' and 'instance' are incompatible. Type 'Input' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 284 more.
如何定义 Input 组件 ref 的类型?
解决方案
any
如果您没有在函数定义/组件中使用它,则不需要为 props 添加通用参数。
const Child = forwardRef<HTMLInputElement>((props, ref) => {
return <Input ref={ref} />;
});
关于 forwardRef 的简短说明。它是一个泛型函数,具有 ref 和 props 类型的类型参数。
const comp = React.forwardRef<RefType, PropsType>((props, ref) => {
return someComp;
});
你会对泛型参数(ref 然后是 props)的顺序感到困惑,这与函数参数(props 然后 ref)的顺序相反。
推荐阅读
- windows - ClearType:使用着色器更改颜色 (Windows)
- python - Pandas - 保证列存在后数据透视表
- python - 如何从一个数据框创建堆叠折线图
- java - Java、Postgres、Redis:PostConstruct 没有完全工作?
- rundeck - Rundeck EC2 插件区域
- python - 在函数python中返回值的问题
- r - 我该如何解决这个错误:“错误:'closure'类型的对象不是一个子集”在闪亮的APP中使用数据表
- django - 从 Django/Graphql 导出 CSV
- azure - 与 Azure Function 一起使用的存储帐户上的高文件 IO 活动
- java - 二叉树的搜索功能未返回找到的节点