react-useLayoutEffect

2 min read
Table of Contents

主要作用

核心特点

注意事项

总结

我们可以使用useLayoutEffect来处理DOM操作

tsx
import React, { useLayoutEffect, useEffect, useRef } from 'react'
export default function App() {
const scrollHandler = (e: React.UIEvent<HTMLDivElement>) => {
const scrollTop = e.currentTarget.scrollTop
window.history.replaceState({}, '', `?top=${scrollTop}`)
}
const container = useRef<HTMLDivElement>(null)
useLayoutEffect(() => {
if (container.current) {
const top = window.location.search.split('=')[1]
container.current.scrollTop = Number(top) || 0
}
})
return (
<div
onScroll={scrollHandler}
ref={container}
id="container"
className="h-[500px] overflow-auto"
>
{Array.from({ length: 500 }).map((_, index) => {
return <div key={index}>{index + 1}</div>
})}
</div>
)
}

后记

My avatar

感谢你读到这里。

这座小站更像一份持续维护的“终端笔记”:记录我解决问题的过程,也记录走过的弯路。


More Posts

评论

评论 (0)

请先登录后再发表评论

加载中...