[英]Animating scrollTop using react-spring
這應該很簡單,但我認為我遺漏了關於 Spring 工作方式的關鍵信息,文檔沒有多大幫助。
我有一個動態列表,用戶可以添加元素,當發生這種情況時,我想使用 React Spring 動畫滾動到頁面底部(由currentBottomY
變量標識)
我有這樣的東西
const mainRef = useRef<HTMLElement | null>(null)
const [y, setY] = useSpring({
from: { y: mainRef?.current?.scrollTop || 0 },
onFrame: props => {
mainRef.current.scrollTop = props.y
},
})
const onAddRow = () => {
setY({ y: currentBottomY })
}
return (
<animated.div ref={mainRef}>
<List />
</animated.div>
)
我收到錯誤消息,說我無法在其中定義from
和onFrame
但在文檔中另有說明,我真的無法對此做出正面或反面,有什么幫助嗎?
如果您想在以后的調用中控制更新(這似乎是您所做的),請嘗試將 function 傳遞給 useSpring 掛鈎。
const [y, setY] = useSpring(() => ({
from: { y: mainRef?.current?.scrollTop || 0 },
onFrame: props => {
mainRef.current.scrollTop = props.y
},
}));
感謝馬特的指針,我解決了這個問題並創建了一個可重用的鈎子,當調用scrollToBottom()
function 時,它接受容器的 ref 並滾動到底部。
import { useSpring } from 'react-spring'
const useScrollAnimation = (
containerRef: React.MutableRefObject<HTMLDivElement | null>
): { animate: () => void } => {
const [, setY] = useSpring(() => ({
y: 0,
onFrame: (props: any) => {
props
},
}))
const scrollToBottom = () => {
setTimeout(() => {
const current = containerRef?.current
if (current) {
const { scrollHeight } = current
setY({
config: { duration: 200 },
y: scrollHeight - current.getBoundingClientRect().bottom,
onFrame: (props: any) => (current.scrollTop = props.y),
})
}
}, 0)
}
return { scrollToBottom }
}
export default useScrollAnimation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.