如何在不使用forwardedRef的情况下使用打字稿在react hoc中创建ref

问题描述

这是我的代码

import React,{
  InputHTMLAttributes,Component,ComponentClass,TextareaHTMLAttributes
} from 'react';


// type TElementType = HTMLInputElement | HTMLTextAreaElement;
// type TAttributesType =
//   | InputHTMLAttributes<HTMLInputElement>
//   | TextareaHTMLAttributes<HTMLTextAreaElement>;

interface IClasstype {
  somevalue: string;
}

type TElementType = HTMLInputElement;
type TAttributesType = InputHTMLAttributes<HTMLInputElement>;

const withInput = (Comp: ComponentClass<TAttributesType>): ComponentClass<IClasstype> => {
  class MyInput extends Component<IClasstype> {
    private refValue = React.createRef<TElementType>();

    componentDidMount() {
      console.log('do something');
    }

    render() {
      return (
        <>
          <Comp
            name="someinput"
            value="somevalue"
            type="text"
            ref={ref => {
              this.refValue = ref;
            }}
          />
        </>
      );
    }
  }

  return MyInput;
};

export default withInput;

这是此错误。refValue = ref:

Type'Component | “ null”不可分配给“ RefObject”类型。 不能将类型“ null”分配给类型“ RefObject”。

我在网上看过,只能找到forwardedRefs的示例。我不需要从传递的组件中转发引用,因为该引用仅在我的临时容器中是必需的。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)