创建通用组件作为
React.forwardRef
这是不可能的
1.
(见下图)。不过,也有一些替代方案——让我们简化一下您的示例以进行说明:
type Option<O = unknown> = { value: O; label: string; }
type Props<T extends Option<unknown>> = { options: T[] }
const options = [
{ value: 1, label: "la1", flag: true },
{ value: 2, label: "la2", flag: false }
]
为了简单起见,选择变体(1)或(2)。(3) 将取代
forwardRef
用通常的道具。(4)你有机会
forwardRef
在应用程序中键入一次定义。
// Given render function (input) for React.forwardRef
const FRefInputComp = <T extends Option>(p: Props<T>, ref: Ref<HTMLDivElement>) =>
<div ref={ref}> {p.options.map(o => <p>{o.label}</p>)} </div>
// Cast the output
const FRefOutputComp1 = React.forwardRef(FRefInputComp) as
<T extends Option>(p: Props<T> & { ref?: Ref<HTMLDivElement> }) => ReactElement
const Usage11 = () => <FRefOutputComp1 options={options} ref={myRef} />
// options has type { value: number; label: string; flag: boolean; }[]
// , so we have made FRefOutputComp generic!
这可以作为
forwardRef
原则上是
plain function
.我们只需要一个通用的函数类型形状。您可以添加一个额外的类型来简化断言:
type ForwardRefFn<R> = <P={}>(p: P & React.RefAttributes<R>) => ReactElement |null
// `RefAttributes` is built-in type with ref and key props defined
const Comp12 = React.forwardRef(FRefInputComp) as ForwardRefFn<HTMLDivElement>
const Usage12 = () => <Comp12 options={options} ref={myRef} />
const FRefOutputComp2 = React.forwardRef(FRefInputComp)
// â³ T is instantiated with base constraint `Option<unknown>` from FRefInputComp
export const Wrapper = <T extends Option>({myRef, ...rest}: Props<T> &
{myRef: React.Ref<HTMLDivElement>}) => <FRefOutputComp2 {...rest} ref={myRef} />
const Usage2 = () => <Wrapper options={options} myRef={myRef} />
3.省略
forwardRef
一起
使用
custom ref prop
相反这是我最喜欢的——最简单的选择,a
legitimate way in React
而且不需要
forwardRef
.
const Comp3 = <T extends Option>(props: Props<T> & {myRef: Ref<HTMLDivElement>})
=> <div ref={myRef}> {props.options.map(o => <p>{o.label}</p>)} </div>
const Usage3 = () => <Comp3 options={options} myRef={myRef} />
4.使用全局类型扩充
添加以下代码
一旦
在你的应用程序中,在一个单独的模块中
react-augment.d.ts
:
import React from "react"
declare module "react" {
function forwardRef<T, P = {}>(
render: (props: P, ref: ForwardedRef<T>) => ReactElement | null
): (props: P & RefAttributes<T>) => ReactElement | null
}
augment
React模块类型声明,重写
带着一个新的
function overload
打字签名。权衡:组件属性,比如
displayName
现在需要一个类型断言。
1.
为什么最初的案例不起作用?
React.forwardRef
有以下类型:
function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>):
ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;
所以这个函数需要
generic
组件式
render function
ForwardRefRenderFunction
,并返回类型为
ForwardRefExoticComponent
.这两个只是函数类型声明
with additional properties
显示名称
,
defaultProps
等
现在,有一个TypeScript 3.4的特性叫做
higher order function type inference
类似于
Higher-Rank Types
。它基本上允许您将自由类型参数(来自输入函数的泛型)传播到外部调用函数-
反应forwardRef
这里-,因此生成的函数组件仍然是通用的。
但正如Anders Hejlsberg在中所解释的那样,该功能只能用于普通函数类型
[1]
,
[2]
:
只有当源类型和目标类型都是纯函数类型时,即具有单个调用签名的类型,我们才进行高阶函数类型推断
没有其他成员
.
上述解决方案将使
反应forwardRef
再次使用泛型。
Playground variants 1, 2, 3
Playground variant 4