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

React组件中Framer Motion动画无法触发问题求助

解决Framer Motion动画不触发的问题

你的代码存在几个关键问题,导致动画未按预期运行:

  • 没有使用motion.div替代普通<div>,Framer Motion的动画API仅对motion组件生效
  • usePresence必须配合父组件的AnimatePresence使用,否则无法正确检测组件的挂载/卸载状态
  • animate.start的调用格式错误,useAnimation的start方法不需要传递DOM元素,应绑定到motion组件上

修正后的代码:

首先确保父组件用AnimatePresence包裹Skill组件,示例如下:

import { AnimatePresence } from 'framer-motion';

// 父组件中
<AnimatePresence>
  {showSkills && skills.map(skill => <Skill key={skill.id} name={skill.name} />)}
</AnimatePresence>

然后修改Skill组件:

import React, { useEffect } from 'react';
import { motion, usePresence, useAnimation } from 'framer-motion';

function Skill(props) {
    const controls = useAnimation();
    const [isPresent, safeToRemove] = usePresence();

    useEffect(() => {
        const runAnimation = async () => {
            if (isPresent) {
                await controls.start({ opacity: 1 });
            } else {
                await controls.start({ opacity: 0 });
                safeToRemove();
            }
        };
        runAnimation();
    }, [isPresent, controls, safeToRemove]);

    return (
        <motion.div 
            className='skill'
            initial={{ opacity: 0 }}
            animate={controls}
            transition={{ duration: 0.5, delay: 0.2 }}
        >
            <h3>{props.name}</h3>
        </motion.div>
    );
}

export default Skill;

更简洁的写法(直接用motion组件内置属性):

如果不需要手动控制动画时序,可省略useAnimation和usePresence,直接依赖AnimatePresence触发动画:

import React from 'react';
import { motion } from 'framer-motion';

function Skill(props) {
    return (
        <motion.div 
            className='skill'
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.5, delay: 0.2 }}
        >
            <h3>{props.name}</h3>
        </motion.div>
    );
}

export default Skill;

父组件仍需用AnimatePresence包裹,且每个Skill组件必须设置唯一key属性。

关键说明:

  • 所有需要动画的元素必须是motion.xxx组件(如motion.div、motion.h3),普通HTML元素无法被Framer Motion的动画系统识别
  • AnimatePresence是实现组件挂载/卸载动画的核心,必须包裹在动态渲染的组件外层
  • usePresence和useAnimation适用于需要手动控制动画流程的场景,简单动画直接使用motion组件的initial/animate/exit属性更高效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 20:06:16