spring react_使用React Spring在React中介绍动画

news/2024/7/7 13:29:05

spring react

In this article we’ll be exploring one of the best animation frameworks for React: React Spring. You’ll learn some of the basics behind changing you component styling into smooth, physics-based transitions.

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

先决条件 (Prerequisites)

React Spring has both a hooks-based and a component-based API, we’ll be exclusively looking at using hooks with basic state for all our animations. So if you need some brushing up on React Hooks, I recommend this article.

React Spring同时具有基于钩子和基于组件的API,我们将专门针对所有动画使用具有基本状态的钩子。 因此,如果您需要对React Hooks进行一些梳理,我建议您阅读本文 。

安装与设定 (Installation and Setup)

Of course, we’re going to need react-spring, and we can just use Create React App to get started.

当然,我们将需要react-spring,我们可以使用Create React App来开始。

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

从和到 (From and To)

In our App.js file we’re going to need useSpring and animated from react-spring.

在我们的App.js文件中,我们将需要useSpring和来自react-spring的 animated

useSpring is a custom hook that we can set our style to, it takes an object with the from and to values as the start and end states while react-spring handles the transition between them. from and to can take objects of almost every css property: color, size, transform, and even our scrollbar. To apply our spring animation, we just need to add animated onto our HTML tags and pass our animation to our style. By default this is run as soon as the component is mounted.

useSpring是一个自定义钩子,我们可以将其设置为样式,它使用一个对象,该对象的fromto值为开始和结束状态,而react-spring处理它们之间的过渡。 fromto可以获取几乎所有CSS属性的对象:颜色,大小,变换,甚至滚动条。 要应用我们的Spring动画,我们只需要在HTML标签上添加animated然后将animated传递给我们的样式即可。 默认情况下,此操作在组件安装后立即运行。

Going from one value to another is maybe a little boring, but react-spring lets us use arrays to render animations with multiple stages. Just remember to always include the starting state with any property you want to add.

从一个值到另一个值可能有点无聊,但是react-spring让我们使用数组来渲染具有多个阶段的动画。 只记得始终将开始状态包括在要添加的任何属性中。

App.js
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)

Adding some local state will allow us to add some actual interactions to our animations, instead of transitioning on mount. Instead of from and to we can use a ternary operator for our single step animations.

添加一些局部状态将使我们能够向动画中添加一些实际的交互,而不必在安装时进行过渡。 对于单步动画to我们可以使用三元运算符来代替from

App.js
App.js
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>
  )
};

(Interpolate)

Besides only adding static style changes to our elements and components we can create more interesting and reusable animations using the interpolate method. We can add variables to our spring, since it is also an object, and use interpolate to extract them for our styles.

除了仅对元素和组件添加静态样式更改之外,我们还可以使用interpolate方法创建更有趣和可重用的动画。 因为它也是一个对象,所以我们可以向其弹簧中添加变量,并使用interpolate将其提取为样式。

We just need to extract our value from our spring and use interpolate to destructure it some more, throw them into some template literals and we’re good to go. This will allow us the freedom to set more dynamic values, like a color value that is based on the x position.

我们只需要从spring中提取我们的值,并使用interpolate对其进行更多分解,将它们放入一些模板文字中 ,我们就很好了。 这将使我们能够自由设置更多的动态值,例如基于x位置的颜色值。

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

  const { xy } = useSpring({
    from: { xy: [0, 0], c: 'green' },
    xy: on ? [800, 200] : [0, 0],
    c: on ? 'red' : 'green'
  });
  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)

One of the more useful aspects of interpolate is that we can emulate CSS keyframes. Instead of passing a value into our spring, we’ll just set it to 1 or 0. Before we can interpolate it like before, we need to pass in an object with a range and an output. Range can be any value between 0 and 1 and works like setting breakpoints with CSS keyframes, the corresponding output is the value that will be prerendered.

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

A second interpolate will then reset our style at every change in output.

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

App.js
App.js
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)

On its own, the previous example is very abrupt and jarring. This is because of react-spring’s default configuration. The animations are mostly based off of a few properties that we are allowed to easily manipulate in our spring. The docs have a wonderful interactive example that really helps to get an intuitive feel for the different properties.

就其本身而言,前面的示例非常突然且令人震惊。 这是由于react-spring的默认配置。 动画主要基于一些属性,我们可以在春天对其进行轻松操作。 该文档有一个很棒的交互式示例,确实有助于获得不同属性的直观感觉。

  • mass: Affects the speed and how far it overshoots the transition.

    mass :影响速度及其对过渡的超调程度。

  • tension: Affects the overall velocity.

    tension :影响整体速度。

  • friction: Controls the resistance and how quickly it decelerates.

    friction :控制阻力及其减速的速度。

  • clamp: Whether it should ever overshoot the transitions.

    clamp :是否过冲过渡。

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

To help us out the team at react-spring even included some configuration presets we can import that will be very useful.

为了帮助我们在React Spring团队工作,甚至包括一些配置预设,我们可以导入这些配置预设将非常有用。

  • config.default { mass: 1, tension: 170, friction: 26 }

    config.default {质量:1,张力:170,摩擦:26}

  • config.gentle { mass: 1, tension: 120, friction: 14 }

    config.gentle {质量:1,张力:120,摩擦:14}

  • config.wobbly { mass: 1, tension: 180, friction: 12 }

    config.wobbly {质量:1,张力:180,摩擦:12}

  • config.stiff { mass: 1, tension: 210, friction: 20 }

    config.stiff {质量:1,张力:210,摩擦:20}

  • config.slow { mass: 1, tension: 280, friction: 60 }

    config.slow {质量:1,张力:280,摩擦:60}

  • config.molasses { mass: 1, tension: 280, friction: 120 }

    config.molasses {质量:1,张力:280,摩擦:120}

App.js
App.js
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
    }
  });

结论 (Conclusion)

While the examples here may not have been the most flashy, I hope that they are enough to help you understand the basics behind React animations using react-spring. ✨

尽管这里的示例可能并不是最华丽的示例,但我希望它们足以帮助您了解使用react-spring的React动画的基础知识。 ✨

翻译自: https://www.digitalocean.com/community/tutorials/react-intro-to-react-spring

spring react


http://www.niftyadmin.cn/n/3649764.html

相关文章

中国大学的集体堕落---麒麟vs汉芯

贴文不说话&#xff1a;“今年年初的时候&#xff0c;我发现FreeBSD的官方网站以及全球最大的开源网站SourceForge曾经一度被封&#xff0c;并且对于FreeBSD使用的是关键字过滤的极端方式封锁。联系这一系列事件&#xff0c;我不得不对年初的FreeBSD被封事件产生了一个可怕的怀…

[收藏]该怎么做,才能取得转型的成功呢?[人力资本]

看了《人力资本》这期的转型专题&#xff0c;给出了几个成功人士的故事&#xff0c;虽然有点老生常谈&#xff0c;不过作为辅助教材&#xff0c;还是有很大指导意义的。刘述尧作为技术人员转型的标杆&#xff0c;谈的感想都蛮现实的&#xff1a;“我上学时候的理想就是将来创办…

命令行 上下箭头符号_命令行基础知识:符号链接

命令行 上下箭头符号Symbolic links allow you to links files and directories to other files and directories. They go by many names including symlinks, shell links, soft links, shortcuts, and aliases. At a glance, a symbolic link looks like just a file or dir…

golang 延迟_了解Go中的延迟

golang 延迟介绍 (Introduction) Go has many of the common control-flow keywords found in other programming languages such as if, switch, for, etc. One keyword that isn’t found in most other programming languages is defer, and though it’s less common you’…

如何安装svelte_在Svelte中使用if块

如何安装svelteIn this tutorial, we’ll see how to use the if blocks with the Svelte framework to add some flow control logic to our Svelte markup code. 在本教程中&#xff0c;我们将看到如何在Svelte框架中使用if块向Svelte标记代码添加一些流控制逻辑。 Blocks i…

[EntLibFAQ]“不允许所请求的注册表访问权”的解释[0508Update]

[EntLibFAQ]“不允许所请求的注册表访问权”的解释VersionDateCreatorDescription1.0.0.12006-5-2郑昀Ultrapower草稿继续阅读之前&#xff0c;我们假设您熟悉以下知识&#xff1a;n Microsoft Enterprise Library June 2005n EventLog和注册表的关系[现象]首先…

mac node repl_如何使用Node.js REPL

mac node replThe author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program. 作者选择了“ 开放互联网/言论自由基金会”作为“ Write for DOnations”计划的一部分来接受捐赠。 介绍 (Introduction) The Node…

[Remoting FAQ]传递Remoting参数时遇到的两种常见错误

[Remoting FAQ]传递Remoting参数时遇到的两种常见错误VersionDateCreatorDescription1.0.0.12006-4-25郑昀Ultrapower草稿继续阅读之前&#xff0c;我们假设您熟悉以下知识&#xff1a;n Remoting[现象1]我们先来描述一个简单的错误。当你激活远端Remoting Objects时&a…