2

这是我的代码

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' }'。

4

1 回答 1

0

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

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

游乐场链接

于 2020-10-13T08:27:44.583 回答