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> ) }