antd中组件切换动画效果
时间: 2023-08-18 20:15:24 浏览: 50
Ant Design提供了一个动画组件 `CSSTransition`,可以用来实现组件切换动画效果。
使用步骤如下:
1. 安装依赖
```bash
npm install react-transition-group --save
```
2. 引入组件
```js
import { CSSTransition } from 'react-transition-group';
import 'animate.css/animate.min.css'; // 引入动画库
```
3. 定义动画 CSS 类
在 `animate.css` 中选择一个适合的动画效果,例如 `fadeIn`。然后定义一个新的 CSS 类,如下所示:
```css
.fadeIn-enter {
opacity: 0;
}
.fadeIn-enter-active {
opacity: 1;
transition: opacity 500ms ease-in;
}
.fadeIn-exit {
opacity: 1;
}
.fadeIn-exit-active {
opacity: 0;
transition: opacity 500ms ease-out;
}
```
这里定义了四个 CSS 类,分别是:
- `.fadeIn-enter`:组件进入前的状态
- `.fadeIn-enter-active`:组件进入过程中的状态
- `.fadeIn-exit`:组件离开前的状态
- `.fadeIn-exit-active`:组件离开过程中的状态
4. 使用组件
将要动画切换的组件包裹在 `CSSTransition` 组件中,设置 `classNames` 和 `timeout` 属性。`classNames` 属性值为刚才定义的动画 CSS 类名,`timeout` 属性值为动画持续时间。
例如:
```jsx
<CSSTransition
classNames="fadeIn"
timeout={500}
>
{showComponent ? <ComponentA /> : <ComponentB />}
</CSSTransition>
```
这里定义了一个切换动画效果为 `fadeIn`,持续时间为 500 毫秒。`showComponent` 为 true 时展示 `ComponentA`,为 false 时展示 `ComponentB`。
完整代码示例:
```jsx
import React, { useState } from 'react';
import { CSSTransition } from 'react-transition-group';
import 'animate.css/animate.min.css';
const FadeInComponent = () => {
const [showComponent, setShowComponent] = useState(true);
const toggleShowComponent = () => {
setShowComponent(!showComponent);
};
return (
<div>
<button onClick={toggleShowComponent}>切换组件</button>
<CSSTransition
classNames="fadeIn"
timeout={500}
>
{showComponent ? <div>ComponentA</div> : <div>ComponentB</div>}
</CSSTransition>
</div>
);
};
export default FadeInComponent;
```