You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 19:05:27