在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;
}
感谢大家的观看
of course like your web site but you need to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality nevertheless I will surely come again again.
新年快乐!
十天看一部剧,还可以吧
@梦不见的梦 行,谢谢提醒,我优化一下
网站的速度有待提升,每次打开都要转半天还进不来呢
@React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?
@Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品
我们大学那会,献血还给学分~
@ab 我想去学网安,比如网警,但分也贼高😕
@夜 加油,你一样也可以成为程序员的,需要学习资料可以V我