TSX中使用framer-motion的whileInView属性出现类型错误
解决framer-motion中motion.path的whileInView TypeScript类型错误
错误原因
TypeScript未将whileInView识别为motion.path的合法属性,通常源于以下两种情况:
- 使用的framer-motion版本低于v6.4.0(该版本才内置
whileInView特性) - 类型定义未包含该属性
解决方案
方案1:升级framer-motion到最新稳定版
执行终端命令完成升级:
npm install framer-motion@latest # 或使用yarn yarn add framer-motion@latest
升级后TypeScript会自动识别whileInView属性,无需额外配置。
方案2:手动扩展SVGMotionProps类型
若无法升级版本,在组件文件顶部添加类型声明扩展:
import type { SVGMotionProps } from "framer-motion"; declare module "framer-motion" { interface SVGMotionProps<SVGElement> { whileInView?: string | object; } }
方案3:使用useInView钩子手动控制动画
这是旧版本framer-motion的标准实现方式,也能规避类型问题:
import { motion, useInView } from "framer-motion"; import { useRef } from "react"; const LogoIcon = () => { const containerRef = useRef(null); const isInView = useInView(containerRef, { once: true }); const logoAnimation = { initial: { pathLength: -1 }, animate: { pathLength: 1 }, }; return ( <div ref={containerRef}> <Svg viewBox="0 0 140 158"> <motion.path variants={logoAnimation} initial="initial" animate={isInView ? "animate" : "initial"} vectorEffect="non-scaling-stroke" d="..." /> </Svg> </div> ); }; // 其余styled组件代码保持不变
内容的提问来源于stack exchange,提问作者DesignAaron
相关产品推荐
相关产品推荐

