TS+React+ref踩坑

导读

如果在使用ref 时候遇上下面错误可以读一读

错误1

RefObject<PureComponent<{}, {}, any>>”分配给类型“LegacyRef<GroupModal>

错误2

'GroupModal' refers to a value, but is being used as a type here.ts

正文

问题一

import GroupModal from './component/groupModal/groupModal';
class CardManagerPage extends React.PureComponent<CardManagerProps, CardManagerState> {
  private groupModal: React.RefObject<React.PureComponent>;
  public constructor(props: CardManagerProps) {
    this.groupModal = React.createRef();
  }

  public render() {
    return  <GroupModal ref={this.groupModal} />
  }
}

会报一长串错误,主要是

RefObject<PureComponent<{}, {}, any>>”分配给类型“LegacyRef<GroupModal>

只要 private groupModal: React.RefObject<GroupModal>;就可以解决

这时候public还是private的价值就体现出来了。

问题2

考虑到component下不止一个组件,我想在index.ts统一导出,代码如下

import GroupModal from './groupModal/groupModal';
export default {
  GroupModal,
};

使用时

import { GroupModal } from './component';

就会报如下错误

'GroupModal' refers to a value, but is being used as a type here.ts

我粗鲁的翻译一下,这里需要一个类型但是你给了他一个值。
我尝试正面解决这个问题,此处省略1万字

只要在index.tsx这样写就可以

export { default as GroupModal } from './groupModal/groupModal';

最终结果

export { default as GroupModal } from './groupModal/groupModal';
import { GroupModal } from './component';
class CardManagerPage extends React.PureComponent<CardManagerProps, CardManagerState> {
  private groupModal: React.RefObject<GroupModal >;
  public constructor(props: CardManagerProps) {
    this.groupModal = React.createRef();
  }

  public render() {
    return  <GroupModal ref={this.groupModal} />
  }

推荐阅读更多精彩内容