Skip to content

Instantly share code, notes, and snippets.

@fimars
Created December 31, 2024 19:14
Show Gist options
  • Save fimars/111f9d1b43be96b948367ec1f3e35714 to your computer and use it in GitHub Desktop.
Save fimars/111f9d1b43be96b948367ec1f3e35714 to your computer and use it in GitHub Desktop.
spring, scrollvalue, test
import React, { useRef, useEffect, useState } from 'react';
// useScrollValue 钩子
function useScrollValue() {
const [scrollY, setScrollY] = useState(window.scrollY);
useEffect(() => {
const handleScroll = () => {
window.requestAnimationFrame(() => setScrollY(window.scrollY));
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return scrollY;
}
// useSpring 钩子
function useSpring(ref, target, config = {}) {
const { damping = 20, stiffness = 200, mass = 1 } = config;
const valueRef = useRef(target);
const velocityRef = useRef(0);
const rafRef = useRef(null);
useEffect(() => {
const step = () => {
const acceleration = (stiffness / mass) * (target - valueRef.current) - (damping / mass) * velocityRef.current;
velocityRef.current += acceleration * 0.016;
valueRef.current += velocityRef.current * 0.016;
if (ref.current) {
ref.current.style.transform = `translateX(${valueRef.current}px)`;
}
rafRef.current = requestAnimationFrame(step);
};
rafRef.current = requestAnimationFrame(step);
return () => cancelAnimationFrame(rafRef.current);
}, [target, stiffness, damping, mass, ref]);
return valueRef;
}
// App 组件
function App() {
const scrollY = useScrollValue();
const divRef = useRef(null);
useSpring(divRef, scrollY, { damping: 20, stiffness: 200 });
return (
<div style={{height: "200vh"}}>
<div style={{position:"fixed", top:"50%"}}>
<div ref={divRef} style={{ width: '100px', height: '100px', backgroundColor: 'lightblue' }}>
Scroll Me!
</div></div>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment