【发布时间】:2021-03-30 02:54:13
【问题描述】:
我的目标是大型可滚动模式,如果提供给模式的项目发生变化(底部有一个“更多项目”部分应该更改模式内容),模式会自动滚动到顶部。由于我不能使用window 对象,其他来源似乎表明ref 是最好的方法。但是,我在编译时不断收到错误node.current is undefined。
我在其他地方看到,这应该可以通过在 useEffect 挂钩中使用 ref 来避免,因为这将确保 ref 在运行时已被初始化,但这里不会发生这种情况。
const PortfolioModal = ({
open,
handleClose,
item,
setItem,
...props
}) => {
const node = useRef();
useEffect(() => {
node.current.scrollIntoView()
}, [item]);
return (
<Dialog onClose={handleClose} open={open} fullWidth={true} maxWidth='lg'>
<div ref={node}></div>
<Content>
{a bunch of stuff is here}
<PortfolioFooter
backgroundImage={`${process.env.PUBLIC_URL}/images/backgrounds/panel5.png`}
item={item}
setItem={setItem}
/>
</FlexContainer>
</Content>
</Dialog>
)
};
编辑:附加说明——我最初用一个带有 ref 的 div 包装了整个组件并尝试使用 scrollTop 并且我没有收到错误,但也没有滚动,所以我想我会尝试使用scrollIntoView 带有一个不可见的元素。
【问题讨论】:
-
查看 Dialog 组件内部,可能它的子组件渲染有延迟
标签: reactjs react-hooks ref