如何使用打字稿在 html 元素的 Hoc 中使用 Ref

How to useRef in Hoc for html element using typescript

这是我的代码

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} 上遇到错误

Type '{ name: string; type: string; value: string; ref: RefObject; }' is not assignable to type 'IntrinsicAttributes & TElementWithAttributes & { children?: ReactNode; }'. Property 'ref' does not exist on type 'IntrinsicAttributes & TElementWithAttributes & { children?: ReactNode; }'.

refReact.DetailedHTMLProps 添加到 html 道具中,这就是您收到错误的原因。尝试:

type TElementType = HTMLInputElement | HTMLTextAreaElement;
type TElementWithAttributes = React.DetailedHTMLProps<InputHTMLAttributes<TElementType>, TElementType>

Playground Link