我可以在react中找到ref对象内的元素吗?

问题描述 投票:0回答:2

我尝试使用 ref getElementByClassName 但错误是 getElementByClassName 不是函数,我无法对指定元素使用 ref。有人可以帮忙吗?

const ref = useRef(null);
//...
const handleAction = () => {
    if(ref.current) {
        console.log('I get here')
        const elem = ref.current.getElementByClassName('myClass')
    }
}

return (<div>
     <component ref={ref} />
     <button onClick={handleAction} />
</div>)

我到达了console.log('我到达这里')

reactjs ref
2个回答
1
投票

将语句更改为

const elem = ref.current.getElementsByClassName('myClass')

函数名称包含

elements
(复数)而不包含
element

此外,它还返回所有匹配元素的数组。


0
投票

如果您想要获取的组件中没有类,那么您可以使用

getElementsByTagName
。更多方法请参见这里

例如:

this.textInput.current.getElementsByTagName('textarea')
© www.soinside.com 2019 - 2024. All rights reserved.