
在上篇文章中,我们了解了 useMotionValue 的基本用法和重要性。今天,我们将聚焦于另一个强大的 Hook:useTransform。useTransform 的作用是将一个或多个 MotionValue 映射到新的 MotionValue,从而实现各种复杂的视觉效果。
什么是 useTransform?
useTransform 是一个 Framer Motion Hook,它接收一个或多个输入的 MotionValue,并根据你提供的转换规则(可以是转换函数或查找表),生成一个新的 MotionValue 作为输出。这个新的 MotionValue 可以被应用到元素的样式或其他动画属性上,从而创建出基于输入值的动态变化。
基本用法:使用转换函数
最灵活的使用方式是提供一个转换函数。这个函数接收输入的 MotionValue 的当前值作为参数,并返回你希望输出的新值。
import {
motion, useMotionValue, useTransform } from "framer-motion";
import {
useEffect } from "react";
function MyComponent() {
const scrollY = useMotionValue(0);
useEffect(() => {
const unsubscribe = window.addEventListener("scroll", () => {
scrollY.set(window.scrollY);
});
return () => window.removeEventListener("scroll", unsubscribe);
}, [scrollY]);
// 将 scrollY 的值映射到 opacity,当 scrollY 从 0 变化到 500 时,opacity 从 1 变化到 0
const opacity = useTransform(scrollY, (value) => {
if
订阅 FreeMac
每周精选:Mac 高效技巧、免费替代付费软件、开发者工具推荐。用对你的 MacBook,省钱 + 提效。