博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
react spring_使用React Spring创建动画的React应用
阅读量:2510 次
发布时间:2019-05-11

本文共 14194 字,大约阅读时间需要 47 分钟。

react spring

One thing that is pivotal to creating great interactive web applications is animations. Animations add life to your applications and improve the overall user experience.

动画对于创建出色的交互式Web应用程序至关重要。 动画可以为您的应用程序增添生气,并改善整体用户体验。

In this tutorial, we'll be looking at how to create simple yet lovely animations in your React apps using an npm package called react-spring, specifically, the Spring component of the package.

在本教程中,我们将研究如何使用一个名为react-spring的npm包(特别是该包的Spring组件)在React应用中创建简单而可爱的动画。

is a great animation package that has been endorsed by some of the React core team including Dan Abramov, and is generally considered one of the best animation packages for React apps out there. It utilises spring like physics in its core animations making it easy to configure. In this tutorial we'll be focused on the Spring component which is one of react-spring's easier to use and more flexible components.

是一个很棒的动画程序包,已被包括Dan Dan Abramov在内的一些React核心团队认可,并且通常被认为是React应用程序中最好的动画程序包之一 。 它在其核心动画中利用了像物理一样的弹簧,因此易于配置。 在本教程中,我们将重点介绍Spring组件,它是react-spring易于使用和更灵活的组件之一。

With Spring we are able to:

使用Spring,我们能够:

  • Manipulate values(numbers)of any sort from measurement units to actual data.

    处理从测量单位到实际数据的各种值(数字)。

  • Manipulate HTML attributes

    处理HTML属性

  • Manipulate SVG paths

    操纵SVG路径

  • Adjust CSS

    调整CSS

And much more!

以及更多!

Springs are cumulative, meaning they'll remember all values passed to them. Let's look at how we can get started with Springs, complete with an example making use of the newly announced React Hooks.

弹簧是累积的,这意味着它们会记住传递给它们的所有值。 让我们看一下如何开始使用Springs,并结合一个示例,充分利用新发布的React Hooks。

( )

( )

We'll be building a simple sliding and fading animation to show you how easily you can achieve animations.

我们将构建一个简单的滑动和淡入淡出的动画,向您展示如何轻松实现动画。

( )

We'll be setting up our React environment with create-react-app which will also generate some boilerplate code that will allow us to get started. To install it run

我们将使用create-react-app设置我们的React环境,该环境还将生成一些样板代码,使我们可以开始使用。 要安装它运行

npm install -g create-react-app

Now you can use it to create your app. Run:

现在,您可以使用它来创建您的应用程序。 跑:

create-react-app react-spring-demo

A folder named react-spring-demo will be created containing our project. Cd into that directory and install our primary dependency, the react-spring package by running:

将创建一个名为react-spring-demo文件夹,其中包含我们的项目。 将CD放入该目录,并通过运行以下命令安装我们的主要依赖关系: react-spring软件包:

yarn add react-spring

You will notice we're using yarn as the package manager for this project as it is the default package manager used by create-react-app. Make sure to have yarn installed by running

您会注意到我们正在使用yarn作为该项目的程序包管理器,因为它是create-react-app使用的默认程序包管理器。 确保通过运行安装纱线

npm install -g yarn

We are now set up to go, let's create our first animated page.

现在我们要开始了,让我们创建第一个动画页面。

( )

Spring can be used to animate styles, to do this, we'll use it to animate the transition into a newly loaded page. To do this we'll wrap the jsx context of App.js in a Spring component.

Spring可以用来为样式设置动画,为此,我们将使用它来设置到新加载页面的过渡的动画。 为此,我们将App.js的jsx上下文App.js在一个Spring组件中。

The Spring component will take two props, from and to which represents the values to be interpolated by our animation.

Spring组件将带有两个propfrom to分别代表我们的动画要插入的值。

In our case we want to create the effect of a page dropping down from above and fading in. To do this, we'll set the initial top margin of the page elements to be a negative value and bring it to 0 during the animation creating a dropping motion. To create the fade in effect, we'll set the initial value of the opacity to 0 and bring that value to 1 at the end of the animation. Luckily for us, the boilerplate generated by create-react-app has the perfect background to show this effect at work so we won't need to change it for now.

在我们的例子中,我们要创建页面从上下拉下并渐入的效果。为此,我们将页面元素的初始上边距设置为负值,并在动画创建期间将其设为0下降的动作。 要创建淡入效果,我们将不透明度的初始值设置为0并在动画结束时将该值设为1 。 对我们来说幸运的是,由create-react-app生成的样板具有完美的背景,可以在工作中显示这种效果,因此我们现在不需要进行更改。

This is what it will look like in our App.js file:

这是我们App.js文件中的App.js

App.js (App.js)

//import React , { Component } from 'react' ;import logo from './logo.svg' ;import './App.css' ;import { Spring  } from 'react-spring' ;class App extends Component {  render ( ) {    return (        < Spring from = { { opacity : 0 , marginTop : - 1000 } } to = { { opacity : 1 , marginTop : 0 } } >          { props => (            < div  className = "App" style = { props } >              < div >                < header className = "App-header" >                    < img src = { logo } className = "App-logo" alt = "logo" / >                    < p >                      Edit < code > src / App . js < / code > and save to reload .                    < / p >                      < a                        className = "App-link"                        href = "https://reactjs.org"                        target = "_blank"                        rel = "noopener noreferrer"                      >                      Learn React                    < / a >                  < / header >                < / div >              < / div >            )          }        < / Spring >    ) ;  }}export default App ;

Now fire up your application by running this command.

现在,通过运行此命令启动您的应用程序。

yarn start

Your browser will open up and you should see the page load with the contents having the desired drop and fade in animations.

您的浏览器将打开,您将看到页面加载,其中的内容具有所需的动画拖放效果。

Nice, isn't it? You can use spring to create any even more style animations adjusting a variety of styles. It is however advised to stick to animating opacity and translations to keep your app light.

很好,不是吗? 您可以使用spring来创建更多甚至可以调整各种样式的样式动画。 但是,建议您坚持设置动画不透明性和翻译效果,以保持应用程序的轻便。

( )

Animating styles is great but we can also use Spring to animate the value of contents shown on the screen. To show this, we'll be creating a counter that starts at 0 and ends at 10 using Spring. As expected, from will hold our initial value and to will hold the final value to be displayed.

动画样式很棒,但是我们也可以使用Spring来动画显示在屏幕上的内容的值。 为了说明这一点,我们将使用Spring创建一个从0开始到10结束的计数器。 与预期一样, from将保留我们的初始值,而to将保留要显示的最终值。

Under the src directory, create a folder called components and in it a file called Counter.jsx. Add the following code to Countrt.jsx :

src目录下,创建一个名为components的文件夹,并在其中创建一个名为Counter.jsx的文件。 将以下代码添加到Countrt.jsx

//src/Counter.jsximport React from 'react' ;import { Spring } from 'react-spring' ;const counter = ( ) => (    < Spring        from = { { number : 0 } }        to = { { number : 10 } }       { props => < div > { props . number . toFixed ( ) } < / div > }    < / Spring >)export default counter ;

Now import our counter into App.js and add it under the header element to render it in our app.

现在,将我们的计数器导入App.js并将其添加到header元素下,以将其呈现在我们的应用程序中。

//App.js...import Counter from './components/Counter' ;class App extends Component {  render ( ) {    return (        < Spring from = { { opacity : 0 , marginTop : - 1000 } } to = { { opacity : 1 , marginTop : 0 } } >          { props => (            < div  className = "App" style = { props } >              < div >                < header className = "App-header" >                    < img src = { logo } className = "App-logo" alt = "logo" / >                    < p >                      Edit < code > src / App . js < / code > and save to reload .                    < / p >                      < a                        className = "App-link"                        href = "https://reactjs.org"                        target = "_blank"                        rel = "noopener noreferrer"                      >                      Learn React                    < / a >                    < Counter / >                  < / header >                < / div >              < / div >            )          }        < / Spring >    ) ;  }}export default App ;

Opening up your browser you will notice the counter just under the Learn React text, like this: delay prop which will be equated to a value in milliseconds, this is the amount of time our animation will wait before starting. Adding a 1 second delay, the counter function will now look like this:

打开浏览器,您将在Learn React文本下方看到计数器,如下所示:

仅一招,我们的动画就发生了这么快,以至于我们在初始页面为可见性设置动画时错过了大部分动画。 幸运的是,我们可以通过添加一个
delay道具来延迟动画,该
delay道具将等于一个以毫秒为单位的值,这是动画在开始播放之前将等待的时间。 添加1秒的延迟,计数器功能现在将如下所示:
const counter = ( ) => (    < Spring        from = { { number : 0 } }        to = { { number : 10 } }        delay = '1000' >        { props => < div > { props . number . toFixed ( ) } < / div > }    < / Spring >)

Checking the browser, the counter now starts after the page animations are finished. Another method we can use to add this delay is through the config prop which we'll come to when discussing the Spring configurations shortly.

现在,检查浏览器后,页面动画结束后计数器开始计数。 我们可以用来增加此延迟的另一种方法是通过配置属性,稍后讨论Spring配置时将使用该属性。

( )

As mentioned before,Springs are physics based. This means we don't have to manually deal with durations and curves. This is great as it takes away some of the heavy math we may have to cover. However, we can still adjust the behaviour of our Spring by tweaking it's tension, friction, delays, mass and other behaviour through the config prop.

如前所述,弹簧是基于物理学的。 这意味着我们不必手动处理持续时间和曲线。 这很棒,因为它消除了我们可能必须涵盖的一些繁琐的数学运算。 但是,我们仍然可以通过config道具通过调整弹簧的张力,摩擦力,延迟,质量和其他行为来调整弹簧的行为。

Don't wish to deal with this but still want to adjust your animations? Don't worry, react-spring comes with some inbuilt presets that we can use to tweak our Springs. All we have to do is import config from the react-spring package and feed them to the config prop of the Spring. Before we get confused about which config is which, let's take a look at an example.

不想处理此问题,但仍想调整动画? 不用担心,react-spring带有一些内置的预设,我们可以使用它们来调整Spring。 我们所要做的就是从react-spring包中导入config并将其提供给Spring的config属性。 在我们对哪个配置感到困惑之前,让我们来看一个示例。

import React from 'react' ;import { Spring , config } from 'react-spring' ;const counter = ( ) => (    < Spring        from = { { number : 0 } }        to = { { number : 10 } }        delay = '1000'        config = { config . molasses } >        { props => < div > { props . number . toFixed ( ) } < / div > }    < / Spring >)export default counter ;

In the example above, we've used the molasses preset which is a high tension, high friction preset provided by react-spring . The presets typically define the tension and friction properties of out Spring. These presets include molasses, default, slow, stiff and wobbly.

在上面的示例中,我们使用了molasses预设,它是react-spring提供的高张力,高摩擦的预设。 预设通常定义外弹簧的tensionfriction特性。 这些预设包括糖蜜,默认,缓慢,僵硬和摆动。

While the presets only define the tension and friction, you can manually configure other properties of the Spring animation which include but are not limited to delay, mass, velocity and duration. For a full list of properties you can configure, along with other options that can be passed as props, check out this page.

虽然预设仅定义张力和摩擦,但是您可以手动配置Spring动画的其他属性,包括但不限于延迟,质量,速度和持续时间。 有关您可以配置的属性的完整列表,以及可以作为道具传递的其他选项,请查看此页面。

( )

The React team recently introduced , this allows us to create functional components that can permanently store data and cause effects, basically adding state to functional components. Hooks are currently only available in React 16.7 alpha as we await a stable release. To use hooks you will need to upgrade to the 16.7 alpha versions of react and react-dom.

React团队最近推出了 ,这使我们能够创建可以永久存储数据并产生影响的功能组件,从而基本上向功能组件添加状态。 当我们等待稳定版本发布时,挂钩仅在React 16.7 alpha中可用。 要使用挂钩,您将需要升级到16.7 alpha版本的reactreact-dom

To do this, run the following commands:

为此,请运行以下命令:

yarn remove react-dom && yarn add react-dom@16.7.0-alpha.0yarn remove react && yarn add react@16.7.0-alpha.0

We can use hooks out of the box with react-spring which exports a hook called useSpring. This hook allows us to define and update data and will generally consist of the same values you would pass as props and useSpring will turn it into animated data. To showcase this, let's look at how we can have more text rendered after our previous animations are done animating.

我们可以使用带有react-spring的开箱即用的钩子,该钩子输出一个称为useSpring的钩子。 这个钩子允许我们定义和更新数据,并且通常包含与道具传递的相同值,而useSpring会将其转换为动画数据。 为了说明这一点,让我们看一下在动画制作完成后如何渲染更多文本。

Here's how we can do that, let's create a new component file called Hooks.jsx and add the following code.

这是我们的操作方法,让我们创建一个名为Hooks.jsx的新组件文件,并添加以下代码。

//Hooks.jsximport React from 'react' ;import { useSpring , animated } from 'react-spring' ;const HookedComponent = ( ) => {    const [ props ] = useSpring ( {        opacity : 1 ,        color : 'white' ,        from : { opacity : 0 } ,        delay : '2000'    } )    return < animated . div style = { props } > This text Faded in Using hooks < / animated . div >}export default HookedComponent ;

We pass the spring settings as an object of arguments to useSpring which will then pass these values to the animated element that then creates our animated spring. We've set our delay to 2000ms to ensure the text from our hooked component fades in after the counter is finished.

我们将弹簧设置作为useSpring的参数对象useSpring ,然后将这些值传递给animated元素,然后创建动画弹簧。 我们将延迟设置为2000ms,以确保计数器完成后,钩子组件中的文本消失。

Now let's import this into App.js and use the HookedComponent in our app. After cleaning up some of the initial boilerplate code from `create-react-app`, it should end up looking like this: Fire up your final application an see the magic.

现在,将其导入App.js并在应用程序中使用HookedComponent 。 在从“ create-react-app”中清除了一些初始样板代码之后,它应该最终看起来像这样:启动最终应用程序,然后神奇。

( )

You now have the tools to get started using react-spring. While it's the easiest to use component of react-spring, Spring provides a simple yet effective means of animating React applications while taking away a huge amount of the workload from the developer.

现在,您已经有了使用React Spring的工具。 虽然它是最容易使用的react-spring组件,但是Spring提供了一种简单而有效的方法来对React应用程序进行动画处理,同时又减轻了开发人员的大量工作量。

Here's the CodeSandbox:

这是CodeSandbox:

You can build on Spring by making use of react-spring's other components such as Transition which animates component lifecycles and Trail which animates the first element of an array and has the rest follow it in a natural trail. Overall, react-spring is a great package with a variety of options depending on your animation needs.

您可以通过使用react-spring的其他组件(例如可对组件生命周期进行动画处理的Transition和可对数组的第一个元素进行动画处理的Trail来构建Spring,而其余元素则可以自然跟踪。 总体而言, react-spring是一个很棒的程序包,根据您的动画需求,可以有多种选择。

翻译自:

react spring

转载地址:http://cguwd.baihongyu.com/

你可能感兴趣的文章
数组Array的API2
查看>>
为什么 Redis 重启后没有正确恢复之前的内存数据
查看>>
No qualifying bean of type available问题修复
查看>>
第四周助教心得体会
查看>>
spfile
查看>>
Team Foundation Service更新:改善了导航和项目状态速查功能
查看>>
WordPress资源站点推荐
查看>>
Python性能鸡汤
查看>>
android Manifest.xml选项
查看>>
Cookie/Session机制具体解释
查看>>
ATMEGA16 IOport相关汇总
查看>>
有意思的cmd命令
查看>>
js正則表達式语法
查看>>
Git学习系列-Git基本概念
查看>>
c#多个程序集使用app.config 的解决办法
查看>>
Linux+Apache+PHP+MySQL服务器环境配置(CentOS篇)
查看>>
Linux下获取本机IP地址的代码
查看>>
(C#)调用Webservice,提示远程服务器返回错误(500)内部服务器错误
查看>>
flex布局
查看>>
python-----python的文件操作
查看>>