在React类组件(非函数式)中使用Framer Motion的动画问题
解决Framer Motion在React类组件中不生效的问题
你代码里的核心问题是**inital属性拼写错误**,正确的属性名应为initial——这是导致动画无法触发的直接原因。
修正后的代码如下:
import {motion} from 'framer-motion' class Sidebar extends React.Component { constructor (props) { super(props) } render (){ return ( <> <motion.section initial={{ width: 0, height: 0, opacity: 0 }} animate={{ width: "100%", height: "100%", opacity: 1 }}> {/* 可添加内容让动画效果更直观 */} </motion.section> </> ) } } export default Sidebar
额外说明:Framer Motion完全支持React类组件,只要保证动画相关属性名称正确即可。如果需要基于状态控制动画切换,可以通过类组件的state管理动画状态,示例如下:
import {motion} from 'framer-motion' class Sidebar extends React.Component { constructor (props) { super(props) this.state = { isSidebarOpen: true } } render (){ return ( <> <motion.section initial={{ width: 0, height: 0, opacity: 0 }} animate={ this.state.isSidebarOpen ? { width: "100%", height: "100%", opacity: 1 } : { width: 0, height: 0, opacity: 0 } }> </motion.section> <button onClick={() => this.setState({ isSidebarOpen: !this.state.isSidebarOpen })}> 切换侧边栏 </button> </> ) } } export default Sidebar
内容的提问来源于stack exchange,提问作者Mohammad
相关产品推荐
相关产品推荐

