如何解决如何使用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>