spring react_如何使用React Spring创建动画的React应用

高胜
2023-12-01

spring react

介绍 (Introduction)

Animations add life to your applications and improve the overall user experience. React Spring is an animation package that uses spring-like physics in its core animations to make it easily configurable. Springs are cumulative, meaning they’ll remember all values passed to them.

动画可以为您的应用程序增添生气,并改善整体用户体验。 React Spring是一个动画程序包,在其核心动画中使用了类似弹簧的物理原理,使其易于配置。 弹簧是累积的,这意味着它们会记住传递给它们的所有值。

With Spring you are able to:

使用Spring,您可以:

  • Manipulate values from measurement units to actual data.

    将值从测量单位转换为实际数据。
  • Manipulate HTML attributes.

    处理HTML属性。
  • Manipulate SVG paths.

    操作SVG路径。
  • Adjust CSS.

    调整CSS。

In this tutorial, you will create a sliding and fading animation in a React app using the Spring component of react-spring.

在本教程中,您将使用react-springSpring组件在React应用程序中创建滑动和淡入淡出的动画。

第1步-配置项目 (Step 1 — Configuring the Project)

You will be setting up the React environment with create-react-app command. This will also generate some boilerplate code that will allow you to get started. To install it, run this command:

您将使用create-react-app命令设置React环境。 这还将生成一些样板代码,使您可以入门。 要安装它,请运行以下命令:

  • npm install -g create-react-app

    npm install -g create-react-app

Now you can use it to create your app:

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

  • create-react-app react-spring-demo

    创建React应用程序React弹簧演示

A folder named react-spring-demo will be created. Move into that directory and install the react-spring package:

将创建一个名为react-spring-demo文件夹。 进入该目录并安装react-spring软件包:

  • yarn add react-spring

    纱线添加React弹簧

You will notice we’re using yarn as the package manager for this project, as it is the default package manager for create-react-app. Ensure it is installed with the following command:

您会注意到我们正在使用yarn作为该项目的程序包管理器,因为它是create-react-app的默认程序包管理器。 确保使用以下命令安装它:

  • npm install -g yarn

    npm install -g纱

Now that things are set up, you are ready to create you first animated page.

设置完成后,就可以创建第一个动画页面了。

第2步-动画样式 (Step 2 — Animating Styles)

Spring can be used to animate styles. In this example you will use it to animate the transition to a newly loaded page. To do this you will wrap the jsx context of App.js in a Spring component.

春天可以用来制作样式的动画。 在此示例中,您将使用它来制作过渡到新加载页面的动画。 为此,您需要将jsx上下文App.jsSpring组件中。

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

Spring组件将采用两个道具fromto ,它们代表要由动画插入的值。

In our case we want to create the effect of a page dropping down from above and fading in. The boilerplate generated by create-react-app has the perfect background to show this effect, so you won’t need to change it for now.

在我们的例子中,我们要创建一个页面从上下拉下并渐入的效果。create create-react-app生成的样板具有完美的背景来显示这种效果,因此您现在无需进行更改。

To achieve the dropping effect, the initial top margin of the page elements will be set to a negative value and brought to 0 during the animation. To create the fade in effect, you’ll set the initial value of the opacity to 0 and bring that value to 1 at the end of the animation.

为了实现拖放效果,在动画过程中,页面元素的初始上边距将设置为负值,并将其设为0 。 若要创建淡入效果,请将不透明度的初始值设置为0并在动画结束时将该值设为1

This is what the App.js file will look like:

这是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;

Fire up your application by running this command.

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

  • yarn start

    纱线开始

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

您的浏览器将打开,您将看到页面加载以及所需的动画降落。

You can use Spring to create even more animations by adjusting a variety of styles. It is advised to stick to animating opacity and translations to keep your app light.

您可以使用Spring通过调整各种样式来创建更多动画。 建议坚持动画不透明度和翻译,以保持您的应用程序轻便。

步骤3 —动画innerText (Step 3 — Animating innerText)

You can also use Spring to animate the value of contents shown on the screen. To show this, you will create a counter that starts at 0 and ends at 10 using Spring. from will hold the 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. In that directory, create a file called Counter.jsx. Add the following code to Countrt.jsx:

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

src/components/Countrt.jsx
src / components / Countrt.jsx
import 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;

Import the counter to App.js and add it under the header element to render it in the app:

将计数器导入App.js并将其添加到header元素下以在应用程序中呈现它:

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

When you open your browser, you will notice the counter under the Learn React text:

打开浏览器时,您会在Learn React文本下看到计数器:

The animation is happening so soon that you are missing it while the initial page is animating into visibility. To fix this, you can delay the animation by adding a delay prop as a value in milliseconds. This is the amount of time the animation will wait before starting.

动画发生得太快了,以至于在初始页面为可见性设置动画时您会丢失它。 要解决此问题,您可以通过添加delay道具作为毫秒值来延迟动画。 这是动画在开始之前将等待的时间。

After adding a one second delay, the counter function will now look like this:

添加一秒的延迟后,计数器功能现在将如下所示:

src/components/Countrt.jsx
src / components / Countrt.jsx
const counter = () => (
    <Spring
        from={{ number: 0 }}
        to={{ number: 10 }}
        delay= '1000'>
        {props => <div>{props.number.toFixed()}</div>}
    </Spring>
)

The counter now starts after the page animations complete. You can also add this delay through the config prop, which will be covered when discussing the Spring configurations.

现在,计数器动画在页面动画完成后开始。 您还可以通过config属性添加此延迟,在讨论Spring配置时将涉及该延迟。

步骤4 —调整弹簧config (Step 4 — Adjusting Spring config)

As mentioned before, Springs are physics based. This means you don’t have to manually deal with durations and curves. This is helpful as it takes away some of the heavy math you may have to cover. However, you can still adjust the behavior of our Spring by tweaking its tension, friction, delay, mass, and other behaviors through the config property.

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

react-spring includes presets that you can use to tweak your Springs. To use them you must import config from the react-spring package and feed them to the config property of the Spring. To prevent any confusion around which config is which, take a look at this example:

react-spring包含可用于调整Spring的预设。 要使用它们,您必须从react-spring包中导入config并将它们提供给Spring的config属性。 为了避免对哪个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, you used the molasses preset. This is a high tension and 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特性。 这些预设包括molassesdefaultslowstiffwobbly

While the presets only define the tension and friction, you can manually configure other properties of the Spring animation. A few examples include 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动画的其他属性。 一些示例包括延迟,质量,速度和持续时间。 有关您可以配置的属性的完整列表,以及可以作为道具传递的其他选项,请查看此页面

步骤5 —使用钩子探索用法 (Step 5 — Exploring Usage with Hooks)

The React team recently introduced React Hooks. React Hooks allows you to create functional components that can permanently store data and cause effects, which adds state to functional components. At the time of this writing, hooks are only available in React 16.7 alpha. To use hooks you will need to upgrade to the 16.7 alpha versions of react and react-dom.

React团队最近推出了React Hooks 。 React Hooks允许您创建可以永久存储数据并产生影响的功能组件,从而为功能组件添加状态。 在撰写本文时,挂钩仅在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.0

    纱线清除react-dom &&纱线添加react-dom@16.7.0-alpha.0
  • yarn remove react && yarn add react@16.7.0-alpha.0

    纱线清除react &&纱线添加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 you to define and update data and will generally consist of the same values you would pass as props. 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 complete.

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

Create a new component file called Hooks.jsx and add the following code:

创建一个名为Hooks.jsx的新组件文件,并添加以下代码:

Hooks.jsx
Hooks.jsx
import 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;

This code passes the spring settings as an object of arguments to useSpring. It will then pass these values to the animated element that creates the animated spring. The delay is set to 2000 milliseconds to ensure the text from the hooked component fades in after the counter is finished.

此代码将spring设置作为useSpring的参数对象useSpring 。 然后它将这些值传递给创建动画弹簧的animated元素。 延迟设置为2000毫秒,以确保来自挂钩组件的文本在计数器完成后淡入。

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. Fire up your final application to review the changes.

现在,将其导入App.js并在应用程序中使用HookedComponent 。 清理了一些来自create-react-app的初始样板代码之后。 启动最终应用程序以查看更改。

结论 (Conclusion)

You have now set up a trial application with react-spring. Spring provides effective means of animating React applications while taking away a large amount of the workload from the developer.

现在,您已经使用react-spring设置了一个试用应用程序。 Spring提供了使React应用程序动画化的有效方法,同时又减轻了开发人员的大量工作量。

You can build on Spring by using react-spring’s other components. Overall, react-spring is includes a variety of options depending on your animation needs.

您可以通过使用react-spring的其他组件在Spring上构建。 总体而言, react-spring包含许多选项,具体取决于您的动画需求。

翻译自: https://www.digitalocean.com/community/tutorials/create-animated-react-apps-with-react-spring

spring react

 类似资料: