【问题标题】:Getting Property 'height' does not exist on type 'string' TypeScript Error获取属性“高度”在“字符串”类型上不存在 TypeScript 错误
【发布时间】:2022-01-19 20:46:55
【问题描述】:

我使用useRef 来引用一个div 元素并存储getBoundingClientRect()。使用它时,我收到了 Property 'height' does not exist on type 'string' 的 TypeScript 错误。如何解决此错误?

const divRef = useRef(null);
const [divSize, setDivSize] = useState("0");

setDivSize(divRef.current.getBoundingClientRect());

console.log(divSize.height); // getting TS error: Property 'height' does not exist on type 'string'.

return (
  <Content ref={divRef}>
     {content}
  </Content>
)

【问题讨论】:

    标签: reactjs typescript use-ref


    【解决方案1】:

    您可以将带有useRef 的泛型类型用于具有getBoundingClientRect 作为有效方法的东西,例如HTMLElementHTMLDivElement

    const divRef = useRef<HTMLDivElement>(null);
    

    这应该允许访问getBoundingClientRect() 的结果的height

    这纯粹是打字的解决方案。 jsejcksn 的回答有助于解释如何以有效的方式处理 falsy/undefined ref。

    【讨论】:

    • 与其他答案类似,我现在收到此错误Argument of type 'DOMRect' is not assignable to parameter of type 'SetStateAction&lt;number&gt;'.
    • @EricNguyen 你真正想保存什么价值?身高是一个数字?作为字符串的高度?整个 DOM rec 对象?目前尚不清楚您要在 state 中保存什么以及保存为什么类型。
    【解决方案2】:

    在任何组件的顶层无条件调用setState 函数始终是错误的,因为它会启动协调算法(无限)。这是 React 文档中的一个注释(需要针对功能组件进行更新):

    可以立即在componentDidUpdate() 中调用setState(),但请注意,它必须像上面的示例一样包含在条件中,否则您将导致无限循环。

    https://reactjs.org/docs/react-component.html#componentdidupdate

    要解决此问题,请将 setState 调用包装在 the effect hook 中:

    const divRef = useRef<HTMLDivElement>(null);
    const [divSize, setDivSize] = useState(new DOMRect());
    
    useEffect(() => {
      if (!divRef.current) return;
      const rect = divRef.current.getBoundingClientRect();
      setDivSize(rect);
      console.log(rect.height);
    });
    
    return (
      <Content ref={divRef}>
         {content}
      </Content>
    )
    

    Also, you can't use the ref prop on a functional component.

    【讨论】:

    • 我试过了,但现在出现了这个错误:Argument of type 'DOMRect' is not assignable to parameter of type 'SetStateAction&lt;number&gt;'
    • @EricNguyen 肯定是setDivSize(divRef.current.getBoundingClientRect().height);。我没有关注这方面,因为错误与参考的输入有关。
    • 啊,我试图避免为变量设置特定值,但想将整个 DOMRect 保存到变量中。
    • @EricNguyen 我现在不在电脑前测试它,但您可以尝试使用以下作为useState 的初始参数而不是0new DOMRect(0, 0, 0, 0)
    • @EricNguyen 我用新的初始状态值更新了我的答案。
    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 2016-03-29
    • 2023-02-21
    • 2021-11-27
    • 2018-08-27
    • 2019-04-12
    • 2020-07-09
    • 2019-10-20
    相关资源
    最近更新 更多