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

如何在Framer Motion中使用自定义React组件替代内置motion元素

解决方案

核心问题说明

  • motion.Comp 语法仅支持 div、span 这类原生HTML标签,自定义组件无法通过这种方式调用
  • motion(Comp) 失效的原因是你的原Comp组件没有将接收的props透传给内部根DOM节点,Framer Motion需要向DOM注入动画相关的属性、事件监听才能正常工作,透传中断就会导致动画不生效

解决步骤

方法1:修改原组件透传props(推荐)

首先调整Comp组件,将所有外部传入的props透传给内部的根元素:

const Comp = (props) => {
    return(
       <div {...props}>
           data here
       </div>
    )
}

如果你的组件使用了forwardRef,还需要同步透传ref:

const Comp = forwardRef((props, ref) => {
    return(
       <div ref={ref} {...props}>
           data here
       </div>
    )
})

之后通过motion()方法包裹组件生成可动画的版本即可使用:

import { motion } from "framer-motion"

const MotionComp = motion(Comp)

const Container = () => {
    return(
       <MotionComp variants={variants} someProp="someProp"/>
    )
}

不需要动画的场景直接使用原Comp组件即可,不会有额外性能损耗,也不会新增多余的DOM包装层。

方法2:使用as属性快速适配

如果不想修改原组件的定义,也可以直接在motion.div上通过as属性指定要渲染的自定义组件,前提依然是原组件要支持透传props:

const Container = () => {
    return(
       <motion.div as={Comp} variants={variants} someProp="someProp"/>
    )
}

这种写法的效果和方法1完全一致,不会生成额外的div元素,最终渲染的就是Comp组件的根节点。


内容的提问来源于stack exchange,提问作者Arash Jahan Bakhshan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:42:04