首页 > 解决方案 > 如何在反应和打字稿中为 forwardRef 扩展引用类型以允许多个引用

问题描述

此代码在打字稿下验证:

type Ref = HTMLTableElement;

const Table = forwardRef<Ref, shapeTable>(({filtered, handleSort, paginationOptions, summary, onMount}, refTable) => {

  useEffect(() => {
    if(refTable && typeof refTable !== 'function' && refTable.current) {
      const tableWidth:string = window.getComputedStyle(refTable.current).getPropertyValue("width");
      onMount(tableWidth);
    }
  }, [refTable, onMount]);

此代码在打字稿下无效:

当我将类型 refTable 放入如下对象中并更新 Ref 类型以允许这样做时,它不会验证。我怎样才能解决这个问题?我需要能够将多个 ref 传递给 forwardRef。我以前没有使用打字稿就这样做了,它可以工作。所以关于 forwardRef 的一些东西似乎坚持只有一种 ref 类型可以通过。除非更新我的 Ref 类型更简单:

键入'((实例:Ref | null)=> void)| 可变引用对象 | null' 不可分配给类型 'Ref'。类型“null”不能分配给类型“Ref”。

type Ref = {
  refTable: HTMLTableElement
};

const Table = forwardRef<Ref, shapeTable>(({filtered, handleSort, paginationOptions, summary, onMount}, ref) => {
  const {refTable}:Ref = ref;

  useEffect(() => {
    if(refTable && typeof refTable !== 'function' && refTable.current) {
      const tableWidth:string = window.getComputedStyle(refTable.current).getPropertyValue("width");
      onMount(tableWidth);
    }
  }, [refTable, onMount]);

标签: reactjstypescript

解决方案


您对哪些属性在哪些对象上感到困惑。在第二个示例中,您有一个具有refTable属性的对象的引用。如果您的 ref 是一个 ref 对象(不是回调 ref),那么它看起来像:

ref = {
  current: {
    refTable: HTMLTableElement,
  }
}

所以你需要先currentref 上寻找,然后在寻找on 。refTableref.current

修改后的代码:

const Table = forwardRef<Ref, shapeTable>(({ filtered, handleSort, paginationOptions, summary, onMount }, ref) => {

  useEffect(() => {
    if (ref && typeof ref !== 'function' && ref.current) {
      const table = ref.current.refTable;
      const tableWidth = window.getComputedStyle(table).getPropertyValue("width");
      onMount(tableWidth);
    }
  }, [ref, onMount]);
  
...

打字稿游乐场链接

请注意,不建议useEffect在依赖项中使用 refs 。


推荐阅读