【问题标题】:How to useRef in Hoc for html element using typescript如何使用打字稿在Hoc中为html元素使用Ref
【发布时间】:2021-01-27 13:18:27
【问题描述】:

这是我的代码

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

【问题讨论】:

    标签: reactjs typescript react-ref react-hoc


    【解决方案1】:

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

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

    Playground Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 2020-07-02
      • 2017-02-14
      • 1970-01-01
      • 2019-12-16
      相关资源
      最近更新 更多