javascript - 如何使用 React Hooks/React Spring 在滚动时淡入元素
问题描述
我正在尝试创建一个动画,其中一个元素根据另一个元素的滚动位置淡化。我能够使用 React Spring 让滚动元素工作,但我正在努力思考如何在没有条件的情况下利用状态钩子,并且只能在组件顶层设置状态。
const HomeView = () => {
const ref = useRef();
const [isVisible, setVisible] = useState(true);
const [{ offset }, set] = useSpring(() => ({ offset: 0 }));
const calc = (o) => {
if (o < 1004) {
return `translateY(${o * 0.08}vh)`;
} else {
// this won't work b/c im trying to useState in a Fn
setVisible(false);
return `translateY(${1012 * 0.08}vh)`;
}
};
const handleScroll = () => {
const posY = ref.current.getBoundingClientRect().top;
const offset = window.pageYOffset - posY;
set({ offset });
};
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
});
return (
<div ref={ref} className="home-view" style={homeViewStyles}>
<div style={topSectionStyles} className="top-content-container"></div>
<animated.div
className="well-anim"
style={{
width: "100vw",
height: "500px",
transform: offset.interpolate(calc),
zIndex: 300,
top: "340px",
position: "absolute"
}}
>
<h1>Well,</h1>
</animated.div>
{/* Trying to fade this component when above animated.div is right above it */}
<h2 style={{ paddingTop: "90px" }} fade={isVisible}>
Hello There!
</h2>
{/***************************************/}
</div>
);
};
解决方案
你快到了。我认为这里的问题在于淡入淡出属性。调用 setVisible 函数没问题。我将根据 isVisible 变量的状态引入第二个弹簧来处理 h2 元素的不透明度。
const {opacity} = useSpring({opacity: isVisible ? 1 : 0});
<animated.h2 style={{ paddingTop: "90px", opacity }} >
Hello There!
</animated.h2>
推荐阅读
- computer-vision - 在 pytorch 中什么是 ([3,128,128]) 和只是 (3,128,128)
- reactjs - 如何在 React.js 中定义仅在身份验证后有效的 PrivateRoute?
- c - 如何将 Swift 对象用作 UnsafeMutablePointer
到 C 函数 - ios - 使用标签栏从另一个视图返回时不调用视图控制器
- python-3.x - Python 3脚本如何在Windows 10开始菜单中添加最近添加的快捷方式?
- javascript - 使用快速 GET 请求从 Mapbox API 接收 2 个响应
- git - 在推送到 Codecommit 时需要特定的提交消息 AWS Lambda
- javascript - 如何创建一个可以改变背景颜色的按钮
- php - 如何以重新打开的形式保持价值?
- sql - Sybase 创建函数(练习)