在 React 中制作动画的最简单方法,或者实际上是在 Web 上的任何地方,都是使用CSS 过渡。
CSS 过渡实际上与 React 无关。引用MDN,
CSS Transitions是 CSS 的一个模块,可让您在特定 CSS 属性的值之间创建渐变。这些转换的行为可以通过指定它们的计时函数、持续时间和其他属性来控制。
因为 CSS 过渡是纯 CSS,它们可以用于 React 应用程序、Angular、纯 Javascript 甚至是完全没有 Javascript 的老式服务器渲染页面。
它不是最通用或最强大的技术。但既然在大多数情况下我们想要的动画都非常简单,那么当一个简单的就可以完成工作时,为什么还要寻找更复杂的东西呢?
除了 Opera Mini 和版本 10 以下的 IE ,所有主流浏览器都很好地支持CSS 过渡。
CSS 过渡使我们能够在两个 CSS 状态之间进行动画处理。假设您想要为抽屉的打开和关闭设置动画(通过单击按钮触发)。假设我们在抽屉周围有一个弹性容器。当抽屉打开时,我们希望它占据容器宽度的 100%,因此它max-width
应该是 100%。当它关闭时,它的宽度应该是 0。我们可以创建两种 CSS 样式:
/* This CSS style is applied when the drawer is opened */
const openedStyle = {
maxWidth: '100%' /* max-with is 100% when the drawer is opened */,
};
/* This CSS style is applied when the drawer is closed */
const closedStyle = {
maxWidth: 0 /* max-width is 0 in the closed drawer */,
};
然后我们处理打开/关闭事件在打开/关闭时将这些类之一应用于抽屉对象:
class Drawer extends React.Component {
state = {
opened: false // Initially search form is Closed
};
toggleOpened = () =>
// Toggle opened / closed state.
// Because we rely on the previous state, we need to use
// a functional setState form
// https://ozmoroz.com/2018/11/why-my-setstate-doesnt-work/
this.setState(state => ({ ...state, opened: !state.opened }));
render() {
const { opened } = this.state;
return (
<div className="drawer-container col-12 col-md-4">
<input
type="text"
className="drawer"
// Apply 'openedStyle' CSS class if the drawer is opened,
// and 'closedStyle' if the drawer is closed.
style={opened ? openedStyle : closedStyle}
/>
<button
type="button"
className="open-close-button btn btn-primary"
onClick={this.toggleOpened}
>
{opened ? 'Close' : 'Open'}
</button>
</div>
);
}
}
export default Drawer;
当我们按下“打开/关闭”按钮时,抽屉将在 0 到 100% 宽度之间翻转,有效地打开和关闭。
![简单的框切换](https://ozmoroz.com/2019/03/react-css-transitions/transition-simple-toggle.gif)
我们现在所需要的就是对其进行动画处理。
为此,我们需要一个秘密成分——CSStransition
属性。我们需要做的就是将以下样式添加到抽屉中:
/* This CSS style is applied when the drawer is opened */
const openedStyle = {
maxWidth: '100%' /* max-with is 100% when the drawer is opened */,
/* Upon transitioning to Open,
animate `max-width' for 0.5s*/
transition: 'max-width 0.5s'
};
/* This CSS style is applied when the drawer is closed */
const closedStyle = {
maxWidth: 0 /* max-width is 0 in the closed drawer */,
/* Upon transitioning to Closed,
animate `max-width' for 0.5s */
transition: 'max-width 0.5s'
};
瞧!我们已经有了动画——点击按钮后,我们的抽屉现在会在半秒内展开和折叠!
![宽度过渡](https://ozmoroz.com/2019/03/react-css-transitions/transition-simple-width.gif)
简而言之,这就是它,但还有更多:
- 您可以使用 CSS 过渡为多个 CSS 属性设置动画。
- 您可以将延迟应用于可转换属性,即首先对不透明度进行动画处理,然后在 0.5 秒延迟后对同一元素的宽度进行动画处理。
- 您可以将各种定时功能应用于转换。
我写了一篇扩展的博客文章来解释以上所有内容:Painless React Animations via CSS Transitions。