reactjs - 强类型 useDynamicCallback

标签 reactjs typescript react-hooks

我正在使用 ag-grid 和 React 并希望使用 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), []);
};

有人可以帮助我使用强类型函数,这样我就可以摆脱任何(如果可能的话)吗?谢谢。

最佳答案

箭头函数中不需要使用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

关于reactjs - 强类型 useDynamicCallback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69286628/

相关文章:

javascript - 如何使用 MySQL 登录 ReactJS、NodeJS?

reactjs - npx create-react-app 每次都花费太长时间

javascript - 每个 React 类方法的 "Missing return type on function"

html - 如何处理鼠标中键的 Angular(单击)事件?

javascript - 如何使用 D3 使用 JSON 数据创建折线图

javascript - 如何在 React 应用程序中保留数据以最小化服务器调用

reactjs - 单例还是 React Context 访问数据访问层函数?

reactjs - 如何跟踪 React 上的页面浏览量

javascript - react native : Passing DataSource into Method from Props in _renderRow

reactjs - JSX.Element' 不可分配给类型 'FunctionComponent<{}>'