簡體   English   中英

使用 ref 不起作用 - counterElement.getElementById 不是函數

[英]use ref didn't work - counterElement.getElementById is not a function

我試圖通過 ref 獲取我的計數器 div,但它給了我一個錯誤“counterElement.getElementById 不是函數”

export default function CountersCube() {
    const counterWrapper = useRef(null)
    
    useEffect(() => {
        const [counterElement] = counterWrapper.current.children
        const counter = counterElement.getElementById("counter");
        console.log(counter)
    })



  return (
    <div className="countersCubeContainer">
        <div ref={counterWrapper}>
                <div id="counter" data-target="60000">0</div>
        </div>
    </div>
  )
}

getElementByIddocument對象的屬性,而不是每個元素的屬性。

使用element.querySelector('#id')代替。

也就是說,具有該 id 的元素counterElement的子元素,因此您不會通過搜索它的后代來找到它。

直接使用counterElement即可。 更好的是,將 ref 放在計數器元素上而不是它的包裝器上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM