【问题标题】:Strongly Types useDynamicCallback强类型使用动态回调
【发布时间】:2021-09-22 14:50:39
【问题描述】:

我正在使用带有 React 的 ag-grid,并希望使用 useDynamicCallback 函数。但是,给定的示例是 js 示例,我想在 typescript 中使用它。

以下是他们拥有的:

function useDynamicCallback(callback) {
    const ref = useRef();
    ref.current = callback;
    return useCallback((...args) => ref.current.apply(this, args), []);
}

以下是我如何添加类型以逃避 ts-lint 错误:

const useDynamicCallback = (callback: any) => {
    const ref = useRef();
    ref.current = callback;
    return useCallback((...args) => (ref as any).current.apply(this, args), []);
};

如果可能的话,有人可以帮助我处理强类型函数吗?谢谢。

【问题讨论】:

    标签: reactjs typescript react-hooks


    【解决方案1】:

    箭头函数中不需要使用this,因为箭头函数是根据定义箭头函数的作用域建立“this”的,直接带参数调用回调即可。见call, apply and bind

    但如果你坚持使用它,这里是类型安全的版本:

    import { useRef, useCallback } from 'react';
    
    type AnyFunction = (...args: any) => any;
    
    function useDynamicCallback(this: ThisParameterType<AnyFunction>, callback: AnyFunction) {
      const ref = useRef<AnyFunction>();
      ref.current = callback;
      return useCallback((...args: Parameters<AnyFunction>) => ref.current?.apply(this, args), []);
    }
    

    TypeScript Playground

    【讨论】:

    • 谢谢。没有“this”关键字的替代方案是什么?
    • @a2441918 ref.current?.(...args)
    • 我只是传播 args 而不是 .apply(this,args)?
    【解决方案2】:
    function useDynamicCallback<T extends (...args: any[]) => any>(callback: T): T {
      const ref = React.useRef(callback);
      ref.current = callback;
      return React.useCallback((...args: unknown[]) => {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-return
        return ref.current.apply(null, args);
      }, []) as T;
    }
    

    【讨论】:

    • 对不起,伙计。这没有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 2019-01-03
    相关资源
    最近更新 更多