(翻译)用react-spring以react hook组件的形式编写动画

3,575 阅读1分钟

原文:alligator.io/react/intro… 在本文中,我们将探索React的最佳动画框架之一:React Spring。 您将学习将组件样式更改为平滑的,基于物理的过渡的一些基础知识。

提前需要了解的

React Spring具有基于钩子和基于组件的API,这里将专门针对所有动画使用具有基本状态的钩子,建议先学习React Hooks相关知识。

环境安装和配置

这里使用Create React App来作为脚手架,另外需要安装react-spring

$ npx create-react-app react-spring-example
$ cd react-spring-example
$ npm i react-spring 

from and to的概念

在下面App.js文件中,使用了react-spring库中的UseSpring和animated,UseSpring是一个可以设置样式的自定义钩子,它接受一个对象,该对象具有from和to值作为开始和结束状态,react-spring正是用这两个状态来处理过渡的动画效果。from和to几乎可以设置所有的CSS属性对象:颜色,大小,transform,甚至滚动条。只需要在HTML标签上增加animated就可以应用spring动画。默认情况下,动画会在组件挂载的时候立即执行。

从一个值过渡到另外一个值可能有点单调,但react-spring可以使用数组来渲染具有多个阶段的动画。只需记住始终将起始状态包含在要添加的任何属性里面即可。

多说无益,下面上代码:

// App.js:
import React, { useState } from 'react';
import { useSpring, animated } from 'react-spring';


const App = () => {
  const animation = useSpring({
    from: { opacity: 0 },
    to: { opacity: 1 }
  });

  const colorAnimation = useSpring({
    from: { color: 'blue' },
    to: { color: `rgb(255,0,0)` }
  });

  const multiAnimation = useSpring({
    from: { opacity: 0, color: 'red' },
    to: [
        { opacity: 1, color: '#ffaaee' },
        { opacity: 1, color: 'red' },
        { opacity: .5, color: '#008000' },
        { opacity: .8, color: 'black' }
    ]
  });
  return (
    <div>
      <animated.h1 style={animation}>Hello World</animated.h1>
      <animated.h1 style={colorAnimation}>Hello World</animated.h1>
      <animated.h1 style={multiAnimation}>Hello World</animated.h1>
    </div>
  )
};

export default App;

State的概念

绑定一些本地状态能够向动画中添加一些实时的效果,而不是在挂载时进行动画效果过渡。 对于单步动画,我们可以使用三元运算符来代替from and to属性。

import React, { useState } from 'react';

const App = () => {
  const [on, toggle] = useState(false);

  const animation = useSpring({
    color: on ? 'blue' : 'red'
  });
  return (
    <div>
      <animated.h1 style={animation}>{!on ? "I'm red" : "Now I'm blue" }</animated.h1>
      <button onClick={() => toggle(!on)}>Change</button>
    </div>
  )
};

Interpolates属性

除了仅对元素和组件添加静态样式更改之外,我们还可以使用Interpolate创建更有趣和可重用的动画。 由于它也是一个对象,因此可以在spring中添加变量,并使用Interpolate获取样式。

我们只需要从spring中取值,并使用Interpolate对其进行更多分解,将其放入模板中。 这将使我们能够自由设置更多的动态值,例如基于x位置的颜色值。

const App = () => {
  const [on, toggle] = useState(false);

  const { xy } = useSpring({
    from: { xy: [0, 0], color: 'green' },
    xy: on ? [800, 200] : [0, 0],
    c: 'red'
  });
  return (
    <div>
      <animated.h1
        style={{ 
            transform: xy.interpolate((x, y) => `translate(${x}px, ${y}px)`), 
            color: c.interpolate(c => c)}}>
        {!on ? "I'm here" : "Now I'm over here"}</animated.h1>
      <button onClick={() => toggle(!on)}>Change</button>
    </div>
  )
};

Mimicking Keyframes

Interpolate更有用的方面之一是我们可以模拟CSS关键帧。与其将值传递到spring中,不如将其设置为1或0。像以前一样Interpolate之前,我们需要传递一个具有范围和输出的对象。 范围可以是0到1之间的任何值,并且可以像使用CSS关键帧设置断点那样工作,相应的输出是将要预渲染的值。

然后,第二次插值将在每次输出更改时重置我们的样式。

const App = () => {
  const [on, toggle] = useState(false)

  const { x, c } = useSpring({
    from: { xy: [0, 0], c: 0 },
    x: on ? 1 : 0,
    c: on ? 1 : 0
  })

  return ( 
    <div>
      <animated.h1
        style={{
          transform: x.interpolate({
            range: [0, .25, .5, .75, 1],
            output: [0, 500, 200, 800, 500]
          }).interpolate(x => `translateX(${x}px)`),

          color: c.interpolate({
            range: [0, .5, 1],
            output: ['red', 'blue', 'green']
          }).interpolate(c => c)
        }}>
        {!on ? "I'm here" : "Now don't know where I'm going"}</animated.h1>
      <button onClick={() => toggle(!on)}>Change</button>
    </div>
  )
}

Config

就其本身而言,前面的示例比较直接和让人惊讶。 这是因为react-spring的默认配置。 我们可以在spring中操作的动画属性如下:

mass:影响速度以及过渡的效果。 tension:影响整体速度。 friction:控制阻力及其减速的速度。 clamp:是否应该瞬间过渡。

const animation = useSpring({
    {/* ... */}
    config: {
      mass: 5,
      tension: 50,
      friction: 25,
      clamp: true
    }
  });

官方提供的一些有用的预设值搭配:

config.default { mass: 1, tension: 170, friction: 26 }
config.gentle { mass: 1, tension: 120, friction: 14 }
config.wobbly { mass: 1, tension: 180, friction: 12 }
config.stiff { mass: 1, tension: 210, friction: 20 }
config.slow { mass: 1, tension: 280, friction: 60 }
config.molasses { mass: 1, tension: 280, friction: 120 }
import { useSpring, animated, config } from 'react-spring';

const animation = useSpring({
    {/* ... */}
    config: config.wobbly
  });
  
// Or you can just destructure it if you want to change other options 
const animation = useSpring({
    {/* ... */}
    config: {
        ...config.molasses, 
        clamp: true
    }
  });