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

如何在TypeScript中结合Framer Motion使用Next.js Link组件?

解决Framer Motion + Next.js Link在TypeScript中的类型错误

问题根源

Framer Motion的motion对象自带的link(小写)对应原生HTML的<a>标签,而你使用的Next.js <Link>是框架自定义组件,不在默认的HTMLMotionComponents类型集合里,所以会触发Property 'Link' does not exist的类型错误。

解决步骤

直接用Framer Motion的motion()方法包裹Next.js的Link组件,生成支持动画能力的自定义组件,同时保留完整的TypeScript类型支持。

修改后的完整代码

import Link from 'next/link';
import { motion } from 'framer-motion';
import styles from './Button.module.css'; // 假设你使用CSS Modules管理样式

// 定义Button组件的类型
type ButtonTypes = {
  href?: string;
  text: string;
  type?: 'button' | 'submit' | 'reset';
  [key: string]: any; // 允许传递其他自定义props
};

// 创建带动画能力的Next.js Link组件
const MotionLink = motion(Link);

export default function Button({ href, text, type = 'button', ...props }: ButtonTypes) {
  if (href) {
    return (
      <MotionLink
        href={href}
        className={`${styles['neon-button']} focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-aquamarine`}
        whileHover={{ scale: 1.1 }}
        whileTap={{ scale: 0.9 }}
        {...props}
      >
        {text}
      </MotionLink>
    );
  }
  return (
    <motion.button
      whileHover={{ scale: 1.1 }}
      whileTap={{ scale: 0.9 }}
      type={type}
      className={`${styles['neon-button']} focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-aquamarine`}
      {...props}
    >
      {text}
    </motion.button>
  );
}

关键说明

  • motion(Link)会把Next.js的Link组件转换成支持Framer Motion动画属性(whileHover、whileTap等)的组件,同时自动继承原组件的类型定义,彻底消除类型错误。
  • 移除了向Link组件传递的无效type参数(Next.js Link不接收该属性),避免不必要的控制台警告。
  • 给type参数设置默认值'button',提升组件的健壮性。

内容的提问来源于stack exchange,提问作者TheInfamousGrim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:42:39