reactjs 如何封装React router NavigateFunction?

csbfibhn  于 2023-10-17  发布在  React
关注(0)|答案(1)|浏览(96)

我希望 Package React路由器的导航功能,以便我可以做一些自定义...
以下是我的尝试:

import { NavigateFunction, NavigateOptions, To, useNavigate } from "react-router-dom"

export function useNavigateCustom(): NavigateFunction {

    const navigate = useNavigate()

    function standardNavigate(to: To, options?: NavigateOptions) {
        // Some customization
        navigate(to, options)
    }

    function deltaNavigate(delta: number) {
        // Some customization
        navigate(delta)
    }

    // What to return here to conform to NavigateFunction interface?
    return {
        ...(standardNavigate as NavigateFunction),
        ...(deltaNavigate as NavigateFunction),
    }
}

在return语句中,我得到了错误:

Type '{}' is not assignable to type 'NavigateFunction'

下面是NavigateFunction的定义:

export interface NavigateFunction {
    (to: To, options?: NavigateOptions): void;
    (delta: number): void;
}
9lowa7mx

9lowa7mx1#

JavaScript中没有函数重载。您必须手动检查参数。
看看typescript中的函数重载

export function useNavigateCustom(): NavigateFunction {
  const navigate = useNavigate();

  function navigateFunction(to: To, options?: NavigateOptions);
  function navigateFunction(delta: number);
  function navigateFunction(toOrDelta: To | number, options?: NavigateOptions) {
    if (typeof toOrDelta === "number") {
      navigate(toOrDelta);
    } else {
      navigate(toOrDelta, options);
    }
  }

  return navigateFunction;
}

相关问题