简体   繁体   English

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

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

im trying to get my counter div by ref, but it gives me an error "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>
  )
}

getElementById is a property of the document object, not of every element. getElementByIddocument对象的属性,而不是每个元素的属性。

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

That said, the element with that id is a child of counterElement so you won't find it by searching it's descendants.也就是说,具有该 id 的元素counterElement的子元素,因此您不会通过搜索它的后代来找到它。

Just use counterElement directly.直接使用counterElement即可。 Better yet, put the ref on the counter element instead of its wrapper.更好的是,将 ref 放在计数器元素上而不是它的包装器上。

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

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