我正在尝试创建一个通用组件,用户可以将自定义 OptionType
传递给组件以进行全程类型检查。该组件还需要一个 React.forwardRef
。
我可以在没有forwardRef的情况下让它工作。有任何想法吗?代码如下:
没有ForwardRef.tsx
export interface Option<OptionValueType = unknown> {
value: OptionValueType;
label: string;
}
interface WithoutForwardRefProps<OptionType> {
onChange: (option: OptionType) => void;
options: OptionType[];
}
export const WithoutForwardRef = <OptionType extends Option>(
props: WithoutForwardRefProps<OptionType>,
) => {
const { options, onChange } = props;
return (
<div>
{options.map((opt) => {
return (
<div
onClick={() => {
onChange(opt);
}}
>
{opt.label}
</div>
);
})}
</div>
);
};
WithForwardRef.tsx
import { Option } from './WithoutForwardRef';
interface WithForwardRefProps<OptionType> {
onChange: (option: OptionType) => void;
options: OptionType[];
}
export const WithForwardRef = React.forwardRef(
<OptionType extends Option>(
props: WithForwardRefProps<OptionType>,
ref?: React.Ref<HTMLDivElement>,
) => {
const { options, onChange } = props;
return (
<div>
{options.map((opt) => {
return (
<div
onClick={() => {
onChange(opt);
}}
>
{opt.label}
</div>
);
})}
</div>
);
},
);
App.tsx
import { WithoutForwardRef, Option } from './WithoutForwardRef';
import { WithForwardRef } from './WithForwardRef';
interface CustomOption extends Option<number> {
action: (value: number) => void;
}
const App: React.FC = () => {
return (
<div>
<h3>Without Forward Ref</h3>
<h4>Basic</h4>
<WithoutForwardRef
options={[{ value: 'test', label: 'Test' }, { value: 1, label: 'Test Two' }]}
onChange={(option) => {
// Does type inference on the type of value in the options
console.log('BASIC', option);
}}
/>
<h4>Custom</h4>
<WithoutForwardRef<CustomOption>
options={[
{
value: 1,
label: 'Test',
action: (value) => {
console.log('ACTION', value);
},
},
]}
onChange={(option) => {
// Intellisense works here
option.action(option.value);
}}
/>
<h3>With Forward Ref</h3>
<h4>Basic</h4>
<WithForwardRef
options={[{ value: 'test', label: 'Test' }, { value: 1, label: 'Test Two' }]}
onChange={(option) => {
// Does type inference on the type of value in the options
console.log('BASIC', option);
}}
/>
<h4>Custom (WitForwardRef is not generic here)</h4>
<WithForwardRef<CustomOption>
options={[
{
value: 1,
label: 'Test',
action: (value) => {
console.log('ACTION', value);
},
},
]}
onChange={(option) => {
// Intellisense SHOULD works here
option.action(option.value);
}}
/>
</div>
);
};
在App.tsx
中,它表示WithForwardRef
组件不是通用的。有没有办法实现这个目标?
示例存储库:https://github.com/jgodi/generics-with-forward-ref
谢谢!
最佳答案
无法直接创建通用组件作为 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) 将用常用的 props 替换 forwardRef
。使用 (4),您可以在应用程序中全局选择 forwardRef
类型定义。
1。使用type assertion (“类型转换”)
// 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} />
2。包裹转发的组件
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 覆盖 forwardRef
类型签名。权衡:像 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 displayName
、defaultProps
等
现在,TypeScript 3.4 有一个名为 higher order function type inference 的功能类似于 Higher-Rank Types 。它基本上允许您将自由类型参数(来自输入函数的泛型)传播到外部,调用函数 - React.forwardRef
这里 -,因此生成的函数组件仍然是泛型的。
但此功能只能与普通函数类型一起使用,正如 Anders Hejlsberg 在 [1] 中解释的那样, [2] :
We only make higher order function type inferences when the source and target types are both pure function types, i.e. types with a single call signature and no other members.
上述解决方案将使 React.forwardRef
再次与泛型一起使用。
关于reactjs - React with Typescript——使用 React.forwardRef 时的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58469229/