繁体   English   中英

使用 generics 在反应中键入 useState 钩子

[英]Typing useState hook in react using generics

有一个自定义的反应钩子来处理文本字段和复选框的输入验证。 使用 generics,因为value可以是字符串或 boolean。

尝试通过setValue设置value会导致错误Argument of type 'Type' is not assignable to parameter of type 'SetStateAction<Type>'.

export function useInputValidation<Type>(_validationFunc = null): InputValidationState<Type> {
  const [isValid, setIsValid] = useState(false);
  const [message, setMessage] = useState("");
  const [value, setValue] = useState<Type>();

  /** handle input of control */
  const handleInput = <Type,>(_value: Type): void => {
    const result =
      _validationFunction === null
        ? { isValid: true, message: "all good" }
        : _validationFunction(_value);

    setMessage(result.message);
    setIsValid(result.isValid);
    setValue(_value);
  };

  return //...
}

我可以通过将 setValue state 键入any来绕过这个问题:

const [value, setValue] = useState<any>();

我在没有 generics 的情况下使用 useState 钩子进行了测试,它工作正常:

const [test, setTest] = useState<string>()
setTest("someText")
console.log(test)

我假设我需要以不同的方式键入我的 useState 挂钩,也许使用 SetStateAction? 现在我不明白为什么我可以使用显式类型而不是泛型来键入 useState 挂钩。

不向useState传递任何参数等同于传递undefined ,因此您应该在通用参数中包含undefined

const [value, setValue] = useState<Type | undefined>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM