javascript - 在 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
更新:尝试使用回调参考,它仍然只显示占位符的高度。尝试调整观察者的大小。但真的希望有一个更简单/开箱即用的方法......
解决方案
所以我使用ResizeObserver解决了它。我修改了这个 repo中的钩子以适合我的项目。
推荐阅读
- java - 如何修复我的 Linechart 十字准线的位置
- javascript - 移至 monorepo 后重新设置分支
- python-3.x - 如何从具有多个 groupby 列的 OHLC 数据中计算枢轴值
- r - 轴的ggplot`expand_scale()` - 不一致
- css - Jupyter 笔记本幻灯片 - 去除侧面的空白
- apache-kafka - 获取相关 ID 为 1 的元数据时出错:kafka 中的 {test1=LEADER_NOT_AVAILABLE}
- node.js - 如何使用 WSO2 EI 集成服务并为使用 MERN 堆栈构建的 Web 应用程序提供 REST API?
- javascript - 表示会话未在中间件中定义,但在控制器中定义
- javascript - 根据剩余时间更改班级
- python - 有没有办法在 Selenium 的浏览器 URL 中输入字符?