網站搜尋

javascript - 在 React/Next.js TypeScript 專案中找不到名稱 "offsetHeight" 或 "clientHeight"


我有一個自訂的可折疊 FAQ 元件,它是基於元素展開時的高度,反之亦然。

import { useState, useRef, useEffect } from "react";

export default FAQItem({title, description}: FAQItemProps) {
  const [isOpen, setIsOpen] = useState(false);
  const heightRef = useRef<HTMLDivElement>(null);

  const collapsible = () => (!isOpen ? setIsOpen(true) : setIsOpen(false));
  
  useEffect(() => {
    !isOpen
      ? (heightRef.current!.style.height = "96px")
      : (heightRef.current!.style.height = `${offsetHeight}px`)
  }, [isOpen]);

  return(
    <div ref={heightRef}>
      <h2 onClick={collapsible}>{title}</h2>
      <p>{description}</p>
    </div>
  )
}

因為我正在處理 TypeScript,所以我找到的一些已經有答案的解決方案不幸地沒有任何與 TypeScript 相關的答案,無法在 TS 中使用,並且需要添加類型定義。結果出現錯誤 Cannot find name "offsetHeight".,而 clientHeight 也會出現相同的情況。

我已嘗試在 offsetHeight 中加入 any,包括:

declare const window: Window & typeof globalThis & {
  offsetHeight: number | any;
}

...正如預期,錯誤消失了,但它並沒有起作用——高度沒有改變,也不會擴展。

然而,我能找到的所有解決方案不幸地都沒有關於在 React TypeScript 專案中獲取元素寬度或高度的 TypeScript 相關答案——它們全部只是純 React 的問題,沒有涉及 TypeScript,而且我也傾向於不使用任何外部庫。

答案#1

你收到錯誤的原因是因為你尚未定義變數 offsetHeight 和 clientHeight。現在,我知道你不需要定義它們,但因為你的使用方式不正確,編譯器認為你忘了創建這些變數。

這是你想要的:heightRef.current?.clientHeight 和 heightRef.current?.offsetHeight,其中的 ? 只是為了在 ref 尚未加載時避免錯誤。

用程式碼編輯

import "./styles.css";
import React from "react";

export default function App() {
  const [isOpen, setIsOpen] = React.useState(false);
  const heightRef = React.useRef<HTMLDivElement>(null);

  const collapsible = () => setIsOpen(!isOpen);

  console.log(isOpen, heightRef.current?.style?.height);

  React.useLayoutEffect(() => {
    if (isOpen) {
      heightRef.current?.style.height = `${heightRef.current?.offsetHeight}px`;
    } else {
      heightRef.current?.style.height = "96px";
    }
  }, [isOpen]);

  return (
    <div className="App" ref={heightRef} style={{height: 1100}}>
      <h1 onClick={collapsible}>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

如果有幫助的話,請接受這個答案!謝謝!

答案#2

看起來你還沒有定義 offsetHeight 變數,卻在這裡引用它

(heightRef.current!.style.height = '${offsetHeight}px')  

這就是為什麼 TypeScript 在報錯。雖然我們不需要定義這個,而是通過這樣獲取值 heightRef.current.offsetHeight。

另外,不要像這樣賦值 heightRef.current!.style.height="96px",應該這樣做 (heightRef.current?.style.height="96px")。據我所知,javascript 中沒有這個運算子 !.。