[英]Get the height (dimensions) of a Suspense element after loading in react
基本上我試圖在 React 中渲染一個非常長的列表(可能是異步的),我只想向上和向下渲染可見條目±10。
我決定獲取保存列表的組件的高度,然后計算整體列表高度/行高,以及滾動 position 來決定用戶滾動的位置。
在下面的例子中, 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
什么也不做。
更新:嘗試使用回調參考,它仍然只顯示占位符的高度。 嘗試調整觀察者的大小。 但真的希望有一個更簡單/開箱即用的方法......
所以我使用ResizeObserver解決了它。 我修改了這個 repo中的鈎子以適合我的項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.