首页 > 其他分享 >[React Typescript] Fixing forwardRef's Type

[React Typescript] Fixing forwardRef's Type

时间:2023-08-29 15:00:04浏览次数:40  
标签:const Fixing React forwardRef props return Type ReactNode

Fix forwardRef globally

To jump ahead to the solution, uncommenting the following code from Stefan Baumgartner will globally override the value of forwardRef:

declare module "react" {
	function forwardRef<T, P = {}>(
		render: (props: P, ref: React.Ref<T>) => React.ReactNode
	): (props: P & React.RefAttributes<T>) => React.ReactNode;
}

This is a good snippet to have on hand when using forwardRef in your TypeScript projects, but there are some tradeoffs, though.

With the above solution, when we go to use ForwardReffedTable, we no longer have access to defaultProps and some of React's other properties even though we do have proper inference for the generic component.

 

Fix forwardRef locally

import { ForwardedRef, forwardRef, useRef } from "react";
import { Equal, Expect } from "../helpers/type-utils";

function fixedForwardRef<T, P = {}>(
  render: (props: P, ref: React.Ref<T>) => React.ReactNode,
): (props: P & React.RefAttributes<T>) => React.ReactNode {
  return forwardRef(render) as any;
}

type Props<T> = {
  data: T[];
  renderRow: (item: T) => React.ReactNode;
};

export const Table = <T,>(
  props: Props<T>,
  ref: ForwardedRef<HTMLTableElement>,
) => {
  return <table ref={ref} />;
};

const ForwardReffedTable = fixedForwardRef(Table);

const Parent = () => {
  const tableRef = useRef<HTMLTableElement>(null);
  const wrongRef = useRef<HTMLDivElement>(null);
  return (
    <>
      <ForwardReffedTable
        ref={tableRef}
        data={["123"]}
        renderRow={(row) => {
          type test = Expect<Equal<typeof row, string>>;
          return <div>123</div>;
        }}
      />
      <ForwardReffedTable
        // @ts-expect-error
        ref={wrongRef}
        data={["123"]}
        renderRow={(row) => {
          return <div>123</div>;
        }}
      />
    </>
  );
};

 

标签:const,Fixing,React,forwardRef,props,return,Type,ReactNode
From: https://www.cnblogs.com/Answer1215/p/17664730.html

相关文章

  • [React Typescript] Strongly type Shared props for multiple components (React.FC<
    import{Equal,Expect}from"../helpers/type-utils";typeInputProps=React.ComponentProps<"input">;constCOMPONENTS={text:(props)=>{return<input{...props}type="text"/>;},number:(p......
  • 【数据结构与算法】TypeScript 实现图结构
    classGrapg<T>{//用于存储所有的顶点verteces:T[]=[];//用于存储所有的边采用邻接表的形式adjList:Map<T,T[]>=newMap();//添加顶点addVertex(v:T){this.verteces.push(v);//初始化顶点的邻接表this.adjList.set(v,[]);}......
  • 设计模式之Prototype模式
    关于这个模式,突然想到了小时候看的《西游记》,齐天大圣孙悟空再发飙的时候可以通过自己头上的3根毛立马复制出来成千上万的孙悟空,对付小妖怪很管用(数量最重要)。Prototype模式也正是提供了自我复制的功能,就是说新对象的创建可以通过已有对象进行创建。在C++中拷贝构造函数(CopyConstr......
  • opencv-python报错:Exception: Not found: 'python/cv2/py.typed'
    报错:self).run_setup(setup_script=setup_script)File"/tmp/pip-build-env-zsqslesq/overlay/lib/python3.6/site-packages/setuptools/build_meta.py",line158,inrun_setupexec(compile(code,__file__,'exec'),locals())File&qu......
  • numpy转pillow图像报错TypeError: Cannot handle this data type: (1, 1, 134), <f4 Ty
    报错TypeError:Cannothandlethisdatatype:(1,1,134),<f4,我猜你很可能是在将array数据转换成图片,使用的是函数Image.fromarray()而这个函数处理的是uint8类型,所以你可以使用:print(image.dtype)查看数据类型,不是uint8格式就转换成uint8:Image.fromarray(np.uint8(ima......
  • [React Typescript] Strongly type Render prop
    1.React.ReactNodeimport{useState}from"react";import{createPortal}from"react-dom";import{Equal,Expect}from"../helpers/type-utils";interfaceModalChildProps{isOpen:boolean;openModal:()=>void;......
  • ref() reactive() 声明响应式状态
    ref函数 使用ref函数将普通数据变成响应式数据reactive函数 把对象和数组这类复合数据类型数据变成响应式数据<template> <span> <spanid="num">{{num}}</span> <inputtype="button"value="+1"@click="f1"> <ul> <liv......
  • [React Typescript] Strongly Typing Lazy Loaded Components with Generics
    Navigatingtothetypedefinitionfor lazy by CMD+click inlocalVSCode,orinthe DefinitelyTyped repo.Wecanseethefollowingdefinition:functionlazy<TextendsComponentType<any>>( factory:()=>Promise<{default:T}>):L......
  • TypeScript – Decorator Metadata
    前言在 TypeScript–Decorator装饰器 里,我有提到TypeScript只实现了decorate的特性,把metadata的特性独立了出来。本来我以为还需要等待很长的时间他们才会实现,没想到v5.2既然推出了。哎哟,不错哦!声明:Decorator不是TypeScript语法,它是ECMAScript(AKAJavaScr......
  • TypeScript – Using Disposable
    前言TypeScriptv5.2多了一个新功能叫 Disposable。Dispose的作用是让"对象"离开"作用域"后做出一些"释放资源"的操作。很多地方都可以看到 Dispose概念。比如WebComponent的 disconnectedCallback,Angular组件的 ngOnDestroy。而对象释放资源在其它面向对象......