代码之家  ›  专栏  ›  技术社区  ›  ZiiMakc

从react中的选项推断选择值字符串类型

  •  0
  • ZiiMakc  · 技术社区  · 5 年前

    OptionType 对组件进行类型检查。该组件还需要一个 React.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>
        );
      },
    );
    

    应用程序。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

    谢谢

    0 回复  |  直到 7 年前
        1
  •  81
  •   ford04    5 年前

    创建通用组件作为 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 在应用程序中键入一次定义。

    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} />
    

    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