如何在React TypeScript中渲染动态Framer Motion motion标签
解决React TypeScript中动态渲染Framer Motion标签的类型错误
问题根源
原代码里as的类型ElementType涵盖范围过广(包含自定义React组件),但motion对象仅支持标准HTML标签作为属性,TypeScript无法推断传入的as是motion的合法键,因此触发访问错误。
解决方案步骤
限制
as的类型为Motion支持的HTML标签
利用Framer Motion提供的MotionDOM类型,或手动定义联合类型,确保as只能传入motion支持的标签名称。添加类型断言消除报错
通过类型断言告知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
相关产品推荐
相关产品推荐

