【发布时间】:2021-11-27 17:20:24
【问题描述】:
我正在使用react-virtualized 来防止在超出视图端口时加载长列表中的项目。但是,我在页面顶部有一个按钮,单击该按钮时,将滚动到使用 react-virtualized 呈现的项目。
它使用React.createRef() 将按钮与列表项链接,但由于渲染的项目在 dom 中不存在,所以引用是 null(它适用于被渲染的前几个项目,但不适用于其余项目项目)。
例如,如果我单击按钮 20,则会收到错误 Cannot read properties of null (reading 'getBoundingClientRect') because the ref of the button is null because it's counterpart ref doesn't exist
有没有办法滚动到在 react-virtualized 中渲染的项目?
我创建了一个代码沙箱here 来说明我的意思。
否则,这里是代码sn-p:
export default function App() {
const onClick = (item) => {
window.scrollTo({
top: item.ref.current.getBoundingClientRect().top,
behavior: "smooth"
});
};
const items = arr.map((el) => ({
ref: createRef(),
id: el.id
}));
return (
<div className="App">
{items.map((item) => (
<button onClick={(e) => onClick(item)}>Scroll to {item.id}</button>
))}
<WindowScroller>
{({ height, scrollTop, registerChild }) => (
<div ref={registerChild}>
<AutoSizer disableHeight>
{({ width }) => (
<>
<List
autoHeight
width={width}
height={height}
rowHeight={100}
rowRenderer={({ index }) => {
return (
<div
ref={items[index].ref}
id={`item-${items[index].id}`}
key={items[index].id}
>
{items[index].id}
</div>
);
}}
scrollTop={scrollTop}
rowCount={items.length}
overscanRowCount={100}
/>
</>
)}
</AutoSizer>
</div>
)}
</WindowScroller>
</div>
);
}
【问题讨论】:
标签: javascript reactjs scrolltop scrollto react-virtualized