Heim > Fragen und Antworten > Hauptteil
P粉2933419692023-09-01 09:20:19
我找到了一个解决方案。你只需使用useMotionValueEvent函数来检查是否滚动超过某一点,并将其设置为状态,然后必须将你的子元素(我的图片)包装在motion.div中,同时在外部div中设置类,如下所示:
function Navbar() { const { scrollY } = useScroll(); const [Scrolled, setScrolled] = useState(false); useMotionValueEvent(scrollY, "change", (latest) => { if (latest > 200) { setScrolled(true); } else { setScrolled(false); } }) return ( <div style={{justifyContent: Scrolled? "left" : "center"}} className={styles.icon} > <motion.div layout transition={{type: "spring", stiffness: 700, damping: 30}} > <Image src="/BlackLogo-2.svg" alt="Cg Logo" width={100} height={100} style={{padding: 20,}} priority /> </motion.div> </div> ) }