reactjs - 如何使用打字稿在Hoc中为html元素使用Ref
问题描述
这是我的代码
import React, { FC, InputHTMLAttributes, useEffect, useRef } from 'react';
type TElementType = HTMLInputElement | HTMLTextAreaElement;
type TElementWithAttributes = InputHTMLAttributes<HTMLInputElement>;
interface Props {
submitTouched: boolean;
}
const withInput = (Comp: FC<TElementWithAttributes>): FC<Props> => props => {
const { submitTouched } = props;
const refValue: React.RefObject<TElementType> = useRef(null);
const updateErrors = (val: string) => {
// handle errors
};
useEffect(() => {
if (submitTouched && refValue.current) {
updateErrors(refValue.current.value);
}
}, [submitTouched]);
const InputOrTextarea = (
<>
<Comp name="somename" type="text" value="somevalue" ref={refValue} />
</>
);
return InputOrTextarea;
};
export default withInput;
我在 ref={refValue} 上收到错误
键入'{名称:字符串;类型:字符串;值:字符串;参考:参考对象;}' 不可分配给类型 'IntrinsicAttributes & TElementWithAttributes & { children?: ReactNode; }'。类型'IntrinsicAttributes & TElementWithAttributes & { children?: ReactNode; 上不存在属性'ref' }'。
解决方案
ref
被添加到 html 道具中,React.DetailedHTMLProps
这就是您收到错误的原因。尝试:
type TElementType = HTMLInputElement | HTMLTextAreaElement;
type TElementWithAttributes = React.DetailedHTMLProps<InputHTMLAttributes<TElementType>, TElementType>
推荐阅读
- python - 如何使用 python / json 中的输入在数据之间插入数据?
- java - 单击 java 按钮时执行 MySql 查询
- c# - 如何在 C# 中随机化文本?
- ionic3 - ionic 3 运行时错误:t.resolve 不是函数
- python - 如何获取频道的会员电报
- api - 如何使用 Cirium API 计算航线距离
- flutter - Flutter Streambuilder 映射到 List 对象
- hive - 如何使用 hive-site.xml 设置 hive 表的 tblproperties 或如何通过在 hive-site.xml 中设置属性将所有表创建为事务表
- google-sheets - 如何从用户读取 excel 文件并生成 Google Sheet 文件
- azure - Azure 流分析作业的运行时错误