如何在将useSearchParams钩子传递给props或函数参数时使用它?

huangapple go评论67阅读模式
英文:

how to type useSearchParams hook when passing it to props or function argument?

问题

在我的组件中,我使用了useSearchParams钩子,但当我将该钩子传递给props或函数参数时,无法为参数添加类型。

import { useSearchParams } from 'react-router-dom';
const urlSearchParamState = useSearchParams();
const [searchParams, setSearchParams] = urlSearchParamState;

如何从该钩子中导入类型?

export declare function useSearchParams(defaultInit?: URLSearchParamsInit): [URLSearchParams, SetURLSearchParams];
英文:

I use useSearchParams hook in my component
when i pass hook to props or function argument i can't type parameters

import { useSearchParams } from 'react-router-dom';
const urlSearchParamState = useSearchParams();
const [searchParams, setSearchParams] = urlSearchParamState;

How to import types from hook?

export declare function useSearchParams(defaultInit?: URLSearchParamsInit): [URLSearchParams, SetURLSearchParams];

答案1

得分: 0

URLSearchParams已存在作为内置对象。要获取setter,我们可以使用ReturnType并访问返回的元组的第二个元素:

type SetURLSearchParams = ReturnType<typeof useSearchParams>[1];
英文:

URLSearchParams already exists as a built-in. To get the setter, we can use ReturnType and access the second element of the returned tuple:

type SetURLSearchParams = ReturnType&lt;typeof useSearchParams&gt;[1];

Playground

huangapple
  • 本文由 发表于 2023年3月3日 21:19:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75627592.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定