自定义 useInput 钩子和打字稿错误

时间:2021-01-10 19:27:21

标签: reactjs typescript

我是打字稿的新手。

我做了一个自定义的 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.

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

1 个答案:

答案 0 :(得分:1)

您需要明确说明您要返回的内容。 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];
};