在React中,我们可以使用CSSTransition动画来为组件添加动画效果。CSSTransition是一个高阶组件,它接受一些参数,并返回一个包装了组件的组件。
下面是一个使用CSSTransition动画的例子:
import React,{createRef,PureComponent } from "react";
import { CSSTransition } from "react-transition-group"
import "./style.css"
export class App extends PureComponent{
constructor(props){
super(props)
this.state = {
isShow:true
}
this.sectionRef = createRef()
}
render(){
const { isShow } = this.state
return (
<div>
<button onClick={e => this.setState({isShow: !isShow})}>切换</button>
{/* {isShow && <h2>哈哈哈</h2> } */}
<CSSTransition
nodeRef={this.sectionRef}
in={isShow}
unmountOnExit={true}
classNames="why"
timeout={2000}
appear
onEnter={e => console.log("开始进入动画")}
onEntering={e => console.log("执行进入动画")}
onEntered={ e => console.log("执行进入结束")}
onExit={e => console.log("开始离开动画")}
onExiting={e => console.log("执行离开动画")}
onExited={e => console.log("执行离开动画")}
>
<div className="section" ref={this.sectionRef}>
<h2>哈哈哈</h2>
<p>我是内容,哈哈哈</p>
</div>
</CSSTransition>
</div>
)
}
}
export default App在上面的例子中,我们使用了CSSTransition组件来为h2元素添加动画效果。CSSTransition组件接受一些参数:
in:指定组件是否应该显示。unmountOnExit:指定组件是否应该在退出动画完成后卸载。classNames:指定动画的类名。timeout:指定动画的持续时间。appear:指定组件是否应该在第一次渲染时显示动画。onEnter:指定组件进入动画开始时的回调函数。onEntering:指定组件进入动画执行时的回调函数。onEntered:指定组件进入动画结束时的回调函数。onExit:指定组件离开动画开始时的回调函数。onExiting:指定组件离开动画执行时的回调函数。onExited:指定组件离开动画结束时的回调函数。nodeRef:指定组件的引用。mountOnEnter:指定组件是否应该在进入动画开始时挂载。unmountOnEnter:指定组件是否应该在进入动画开始时卸载。addEndListener:指定组件是否应该添加结束监听器。removeEndListener:指定组件是否应该移除结束监听器。
然后附上style.css的代码:
/* 进入动画 */
.why-appear{
transform: translateX(-150px);
}
.why-appear-active{
transform: translateX(0);
transition: transform 2s ease;
}
.why-appear,.why-enter{
opacity: 0;
}
.why-appear-active,.why-enter-active{
opacity: 1;
transition: opacity 2s ease;
}
/* 离开动画 */
.why-exit{
opacity: 1;
}
.why-exit-active{
opacity: 0;
transition: opacity 2s ease;
}感谢大家的观看
我热爱 旅游专栏。令人惊艳了解路线。
欣赏你的照片, 我明白, 世界很美。感谢 旅行灵感。
读起来像小说。继续保持 带来的灵感。
让人精神焕发的 帖子! 我准备订票了。
以后焦虑了或者迷茫了记得回来看看
我非常喜欢 出行博客。鼓舞人心查看路线。
你们的博客 百分百 帮助选择路线。坚持!
信息丰富的 出行资源! 越来越棒!
My brother suggested I might like this blog. He was entirely right. This post actually made my day. You cann't imagine just how much time I had spent for this information! Thanks!
我热爱, 写得很实在。你的博客 就是 最好的例子。很出色。