首页 > 解决方案 > 在 react 中加载后获取 Suspense 元素的高度(尺寸)

问题描述

基本上我试图在 React 中渲染一个非常长的列表(可能是异步的),我只想向上和向下渲染可见条目±10。

我决定获取保存列表的组件的高度,然后计算整体列表高度/行高,以及滚动位置来决定用户滚动的位置。

在下面的例子中,SubWindow是一个可以容纳列表或图片等的通用组件......因此,我认为它不是计算的最佳位置。相反,我将 calc 移动到不同的组件并尝试使用 ref 代替

const BananaWindow = (props) => {
    const contentRef = useRef(null)

    const [contentRefHeight, setContentRefHeight] = useState(0)

    useEffect(()=>setContentRefHeight(contentRef.current.offsetHeight), [contentRef])

    //calc which entries to include
    startIdx = ... 
    endIdx = ...
    ......

    return ( 
        <SubWindow 
            ref={contentRef} 
            title="all bananas" 
            content={
                <AllBananas 
                    data={props.data} 
                    startIdx={startIdx} 
                    endIdx={endIdx}
                />
            }
        />
    )
}

//this is a more general component. accepts a title and a content
const SubWindow = forwardRef((props, contentRef) => {
    return (
    <div className="listContainer">
        <div className="title">
            {props.title}
        </div>
        <div className="list" ref={contentRef}>
            {props.content}
        </div>
    </div>
})

//content for all the bananas
const AllBanana = (props) => {
    const [data, setData] = useState(null)
    
    //data could be from props.data, but also could be a get request
    if (props.data === null){
        //DATA FETCHING
        setData(fetch(props.addr).then()...)
    }

    return(
        <Suspense fallback={<div>loading...</div>}>
            //content
        </Suspense>
}

问题:在BananaWindow中,useEffect仅在初始安装和绘画时触发。所以我最终只得到offsetWidth了占位符。当内容加载完成useEffect时, 什么都不做。SubWindow

更新:尝试使用回调参考,它仍然只显示占位符的高度。尝试调整观察者的大小。但真的希望有一个更简单/开箱即用的方法......

标签: javascriptreactjsreact-suspense

解决方案


所以我使用ResizeObserver解决了它。我修改了这个 repo中的钩子以适合我的项目。


推荐阅读