首页 > 解决方案 > 自定义 useInput 钩子和打字稿错误

问题描述

我是打字稿的新手。

我做了一个自定义的 useInput 钩子:

export const useInput = (initialValue = "") => {
  const [value, setValue] = useState(initialValue);

  const onChange = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => setValue(e.currentTarget.value),
    []
  );

  return [value, onChange, setValue];
};

我以这样的形式引用这个钩子

  const [deviceInput, bindDeviceInput, setDeviceInput] = useInput();
  const assignUserId = (deviceId: string) => {
    setDeviceInput(deviceId);
  };

value 和 onChange 工作,setValue 给了我这个错误

> This expression is not callable.   Not all constituents of type
> 'string | Dispatch<SetStateAction<string>> | ((e:
> ChangeEvent<HTMLInputElement>) => void)' are callable.
>     Type 'string' has no call signatures.

这是我无法弄清楚的一个打字稿错误。

标签: reactjstypescript

解决方案


您需要明确说明您要返回的内容。Typescript 只是认为您正在返回一个数组,其中每个元素都可以是其他任何元素。我不知道为什么,我觉得这可能是打字稿中的一个错误,没有检查过。

做这个:

type useInputHook<T> = [T, (val: T) => void, Dispatch<SetStateAction<T>>];

export const useInput = <T>(initialValue: T = ""): useInputHook<T> => {
  const [value, setValue] = useState(initialValue);

  const onChange = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => setValue(e.currentTarget.value),
    []
  );

  return [value, onChange, setValue];
};

推荐阅读