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

如何在React TypeScript中渲染动态Framer Motion motion标签

解决React TypeScript中动态渲染Framer Motion标签的类型错误

问题根源

原代码里as的类型ElementType涵盖范围过广(包含自定义React组件),但motion对象仅支持标准HTML标签作为属性,TypeScript无法推断传入的as是motion的合法键,因此触发访问错误。

解决方案步骤

  1. 限制as的类型为Motion支持的HTML标签
    利用Framer Motion提供的MotionDOM类型,或手动定义联合类型,确保as只能传入motion支持的标签名称。

  2. 添加类型断言消除报错
    通过类型断言告知TypeScript,as是motion对象的合法属性键,安全获取对应的motion标签。

完整修正代码

import { type HTMLAttributes } from 'react';
import { motion, type MotionDOM } from 'framer-motion';

// 限定as为motion支持的HTML标签类型
interface IconButtonProps extends HTMLAttributes<HTMLElement> {
  as?: keyof MotionDOM;
}

const IconButton = ({ as = 'button', children, ...restProps }: IconButtonProps) => {
  // 类型断言确认as是motion的合法键
  const Tag = motion[as as keyof typeof motion];

  return (
    <Tag className="block rounded-full p-2" {...restProps}>
      {children}
    </Tag>
  );
};

export default IconButton;

可选:手动定义支持的标签类型

若不想依赖MotionDOM,可手动列出需要支持的标签:

// 手动定义motion支持的标签联合类型
type MotionSupportedTags = 'button' | 'div' | 'span' | 'a' | 'img';

interface IconButtonProps extends HTMLAttributes<HTMLElement> {
  as?: MotionSupportedTags;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 18:01:00