【问题标题】:Typescript errors when using React hooks使用 React 钩子时的打字稿错误
【发布时间】:2021-01-18 10:33:25
【问题描述】:

我正在尝试使用 react useState,useRef 与 Ionic 应用程序中的 typescript 挂钩,并且在尝试访问对象属性时不断出现愚蠢的 typescript 错误。

const [ matrix, updateMatrix ] = useState([]);
updateMatrix([['cell1', 'cell2', 'cell3'], ['cell4', 'cell5', 'cell6']])

在上面的代码中我得到了

“类型 'string' 不可分配给类型 'never'”

const basketEl = useRef(null);
if (basketEl.current) { 
  console.log(basketEl.current.getBoundingClientRect())
}

在上面的代码中,我得到 "Object is possible 'null'" for basketEl.current。即使我放了

if (basketEl.current !== null) {

错误仍然存​​在。 有趣的是,如果我不使用钩子并使用反应类,打字稿错误就会消失。修复ts错误需要花费大量时间,我放弃并开始使用类。也许我用错了钩子?有人同时使用钩子和打字稿有同样的问题吗?

【问题讨论】:

  • 为什么你在使用 typescript 时不输入钩子?

标签: reactjs typescript react-hooks ionic4


【解决方案1】:

您必须指定状态的确切类型,因为它们基于默认值是不明确的。

正确代码:

const [ matrix, updateMatrix ] = useState<string[]>([]);

const basketEl = useRef<Element>(null);

【讨论】:

  • 对于 ref 现在我有这个 ts 错误 Type 'RefObject&lt;Element&gt;' is not assignable to type 'string | ((instance: HTMLDivElement | null) =&gt; void) | RefObject&lt;HTMLDivElement&gt; | null | undefined'. Type 'RefObject&lt;Element&gt;' is not assignable to type 'RefObject&lt;HTMLDivElement&gt;'. Type 'Element' is missing the following properties from type 'HTMLDivElement': align, accessKey, accessKeyLabel, autocapitalize, and 108 more.ts(2322) 当分配 ref &lt;div id="basket" ref={basketEl}&gt; 我以从反应网站分配 null 为例
  • 你试过useRef&lt;HTMLDivElement&gt;(null)吗?
【解决方案2】:

const [ matrix, updateMatrix] = useState&lt;any&gt;([]) 你试过了吗

【讨论】:

    【解决方案3】:

    因为basketEl 为空,因此您不能调用basketEl.current。首先,当组件挂载时,您必须在useEffect 中调用它。其次,打字稿的错误,你可以这样修复:

    useEffect(()=>{
      if(basketEl !== null && basketEl.current !== null){
         console.log(basketEl.current.getBoundingClientRect())
      }
    }, [basketEl])
    

    请尝试一下,我相信它会很好用

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2021-02-14
      • 2021-01-03
      • 1970-01-01
      • 2019-10-28
      • 2019-06-22
      • 2022-07-08
      • 2021-11-25
      • 1970-01-01
      相关资源
      最近更新 更多