如何解决如何使用打字稿在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}上遇到错误
输入'{name:string;类型:字符串;值:字符串; ref:RefObject; }'不能分配给'IntrinsicAttributes&TElementWithAttributes&{children ?: ReactNode; }'。 属性'ref'在类型'IntrinsicAttributes&TElementWithAttributes&{children ?: ReactNode; }'。
解决方法
ref
由React.DetailedHTMLProps
添加到html道具中,这就是为什么您会遇到错误。试试:
type TElementType = HTMLInputElement | HTMLTextAreaElement;
type TElementWithAttributes = React.DetailedHTMLProps<InputHTMLAttributes<TElementType>,TElementType>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。