简体   繁体   English

反应检查元素是否有内部滚动

[英]React check if element has inner scroll

useEffect(() => {
    if (middleRef.current.scrollHeight) {
        console.log(
            middleRef.current.scrollHeight > middleRef.current.clientHeight,
            'loggie'
        );
        let scrollableCheck =
            middleRef.current.scrollHeight > middleRef.current.clientHeight;
        setScrollable(scrollableCheck);
    } else {
        console.log('else');
    }
}, [middleRef.current.scrollHeight]);

With this code I'm trying to find out if the element has a scrollbar or not.使用这段代码,我试图找出元素是否有滚动条。 I think the problem is that when it checks the HTML element isn't rendered yet.我认为问题在于当它检查 HTML 元素时尚未呈现。 I tried all sorts of other examples but nothing seems to work.我尝试了各种其他示例,但似乎没有任何效果。 This code doesn't crash the page but also doesn't do what is should此代码不会使页面崩溃,但也不会执行应有的操作

Some other code I tried:我试过的其他一些代码:

Uncaught TypeError: Cannot read properties of null (reading 'scrollHeight')未捕获的类型错误:无法读取 null 的属性(读取“scrollHeight”)

useEffect(() => {
    let middleId = document.getElementById('middle');
    checkForScrollBar(middleId);
}, []);

function checkForScrollBar(middleId) {
    let scrollableCheck = middleId.scrollHeight > middleId.clientHeight;
    setScrollable(scrollableCheck);
}

_ _

useEffect(() => {
    let scrollableCheck = middleId?.scrollHeight > middleId?.clientHeight;
    setScrollable(scrollableCheck);
}, [middleId.clientHeight]);

It should be a pretty simple thing to check for but I'm a bit lost with what I'm doing wrong.检查应该是一件非常简单的事情,但我对自己做错的事情有点迷茫。

In your first code block, line 2, inside if statement, you should write middleRef.current.scrollHeight not middleRef.scrollHeight .在您的第一个代码块中,第 2 行,在 if 语句内,您应该编写middleRef.current.scrollHeight而不是middleRef.scrollHeight

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

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