Table of Contents
1. Install react-motion animation library
2. Counter case
2. Animation case for changing transparency and width
3.TransitionMotion execution loading and unloading animation case
Home Web Front-end JS Tutorial React uses scripting to implement animation

React uses scripting to implement animation

Apr 14, 2018 pm 04:25 PM
react

This article will share with you how to use scripts to implement animation. To use scripts to implement animation, we can use the react-motion animation library. It is an excellent animation library and uses scripts to implement animations. (motion means movement), which has certain reference value. Friends in need can refer to

react-motion: https://github.com/chenglou/react-motion

1. Install react-motion animation library

yarn add react-motion//ro  npm install react-motion
Copy after login

2. Counter case

This case implements adding the number 0 to 1

React uses scripting to implement animation

1. Import spring and Motion from the react-motion library

spring: Specify how to animate the target value, for example, spring(10, {stiffness: 120, damping: 17}) means "Draw the dynamic value to 10, the spring stiffness is 120, and the damping is 17"

Motion: It is A component that specifically provides animation data. It receives a function as a subcomponent, for example:

< motion >
   { value  => (   ) } 
</ Motion >
Copy after login

2. Motion component attribute:

defaultStyle : Set the default value before the animation starts

style : Set the animation to the value

import React, {Component} from &#39;react&#39;;
import {spring ,Motion} from &#39;react-motion&#39;;

export default class Main extends Component {
    render() {        return (
            <p style={styles.content}>
                {/*由0 过渡到 1 ; stiffness是阻尼*/}
                <Motion defaultStyle={{x: 0}} style={{x: spring(1,{stiffness: 20})}}>
                    {
                        value =>
                            <p>
                                {value.x}
                            </p>
                    }
                </Motion>
            </p>
        )
    }
}/*样式*/const styles = {
    content: {
        width: &#39;400px&#39;,
        height: &#39;500px&#39;,
        backgroundColor: &#39;skyblue&#39;,
        margin: &#39;0 auto&#39;,
    },
}
Copy after login

The effect of execution:

React uses scripting to implement animation

2. Animation case for changing transparency and width

Through the above case, we can know that the Motion group is dedicated to providing animation data. In fact, it does not participate in the drawing of the interface, The drawing process of the interface is completed through subcomponents. Let's do an animation case of changing transparency and width

1. Import spring and Motion2 from the

react-motion

library. The value of value.x transitions from 0 to 1. You can modify the transparency and width of p through the animation data class provided by Motion

3.${value.x} Added backticks on both sides. This is the string template syntax in es6. ${} can be understood as the effect of interpolator

import React, {Component} from &#39;react&#39;;

import {spring ,Motion} from &#39;react-motion&#39;;

export default class Main extends Component {

    render() {        return (
            <p style={styles.content}>
                {/*由0 过渡到 1 ; stiffness是阻尼*/}
                ......

                {/*改变p的宽度和透明度*/}
                <Motion defaultStyle={{x: 0}} style={{x: spring(1,{stiffness: 20})}}>
                    {
                        value =>

                            <p style={ Object.assign({},styles.pStyle,{
                                opacity:`${value.x}`,
                                width:`${50+value.x*100}px`
                            })}>
                                默认
                            </p>
                    }
                </Motion>

            </p>
        )
    }


}/*样式*/const styles = {
    content: {
       ....
    },
    pStyle: {
        width: &#39;50px&#39;,
        height: &#39;50px&#39;,
        backgroundColor: &#39;green&#39;,
        margin: &#39;3px 0&#39;,
        color:&#39;white&#39;
    },
}
Copy after login

refreshing the interface to 0.2:

React uses scripting to implement animation

The result after execution:

React uses scripting to implement animation

3.TransitionMotion execution loading and unloading animation case

The previously learned TransitionGroup animation library provides loading and unloading animations of execution components. In fact, react-motion also provides this function. To use this function, you need to use a new API: TransitionMotion component, which can help you perform component loading and unloading animations. .

1. Import TransitionMotion, spring and presets from the react-motion library

##TransitionMotion is the loading and unloading animation of the execution component

spring : Specify how to animate the target value

presets : Preset the values ​​of stiffness and damping

2. When adding a component: The state is transitioned by the state defined in willEnter() To the state defined in styles

willEnter(){
        return {width: 0, height: 0};}
// 由willEnter()中width: 0, height: 0状态过渡到下面styles中width:200, height: 50状态
// spring() 函数为目标值设置动画
// presets.wobbly 等价于 {stiffness: 180, damping: 12}
 styles={this.state.items.map(item => ({
                        key: item.key,
                        style: {width: spring(item.w,presets.wobbly), height: spring(50,presets.wobbly)},
                    }))}
Copy after login

3. When deleting a component: The state transitions from the state defined in styles to the state defined in willLeave

 styles={this.state.items.map(item => ({
                        key: item.key,
                        style: {width: spring(item.w,presets.wobbly), height: spring(50,presets.wobbly)},
                    }))}
// 由styles中width:200, height: 50状态过渡到下面willEnter()中width: 0, height: 0 状态
// presets.wobbly 等价于 {stiffness: 180, damping: 12}
//下面的 spring(0,presets.wobbly) 设置目标值动画                
willLeave() {
        return {width: spring(0,presets.wobbly), height: spring(0,presets.wobbly)};}
Copy after login

Complete code of the case:

import React, {Component} from &#39;react&#39;;
import {TransitionMotion,spring , presets} from &#39;react-motion&#39;;

export default class Main extends Component {

    constructor(props) {        super(props);        /*定义一个数组:目标状态*/
        this.state={
            items: [{key: &#39;a&#39;, w: 200},{key: &#39;b&#39;, w: 200}],
        }
    }    /*装载组件的状态( 进入/添加组件 )*/
    willEnter(){        return {width: 0, height: 0};
    }    /*御载组件的状态( 离开/删除组件 )*/
    willLeave() {        return {width: spring(0,presets.wobbly), height: spring(0,presets.wobbly)};
    }

    render() {        return (
            <p style={styles.content}>

                <TransitionMotion
                    willEnter={this.willEnter}
                    willLeave={this.willLeave}
                    styles={this.state.items.map(item => ({
                        key: item.key,
                        style: {width: spring(item.w,presets.wobbly), height: spring(50,presets.wobbly)},
                    }))}>

                    {interpolatedStyles =>
                        <p>
                            {interpolatedStyles.map(config => {                                
                            return <p key={config.key} style={{...config.style, border: &#39;1px solid&#39;}} >
                                    {config.key} : {config.style.height}
                                </p>
                            })}
                        </p>
                    }
                </TransitionMotion>
                <button onClick={()=>this.startAnimation(0)}>Add C</button>
                <button onClick={()=>this.startAnimation(1)}>remove C</button>

            </p>
        )
    }

    startAnimation(index){        // add
        if(index==0){            this.setState({
                items: [{key: &#39;a&#39;, w: 200},{key: &#39;b&#39;, w: 200},{key: &#39;c&#39;, w: 200}],
            })        // remove
        }else{            this.setState({
                items: [{key: &#39;a&#39;, w: 200},{key: &#39;b&#39;, w: 200}],
            })
        }

    }

}/*样式*/const styles = {
    content: {
        width: &#39;400px&#39;,
        height: &#39;500px&#39;,
        backgroundColor: &#39;skyblue&#39;,
        margin: &#39;0 auto&#39;,
    },
}
Copy after login
Refresh the default browser state:

React uses scripting to implement animation

After clicking Add C, add a p, and the width and height will slowly become larger

React uses scripting to implement animation


##Related recommendations:

React Animation Effect

Use React to implement page transition animation

ReactJS learning series courses (React animation use)

The above is the detailed content of React uses scripting to implement animation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Animation not working in PowerPoint [Fixed] Animation not working in PowerPoint [Fixed] Feb 19, 2024 am 11:12 AM

Are you trying to create a presentation but can't add animation? If animations are not working in PowerPoint on your Windows PC, then this article will help you. This is a common problem that many people complain about. For example, animations may stop working during presentations in Microsoft Teams or during screen recordings. In this guide, we will explore various troubleshooting techniques to help you fix animations not working in PowerPoint on Windows. Why aren't my PowerPoint animations working? We have noticed that some possible reasons that may cause the animation in PowerPoint not working issue on Windows are as follows: Due to personal

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

How to set up ppt animation to enter first and then exit How to set up ppt animation to enter first and then exit Mar 20, 2024 am 09:30 AM

We often use ppt in our daily work, so are you familiar with every operating function in ppt? For example: How to set animation effects in ppt, how to set switching effects, and what is the effect duration of each animation? Can each slide play automatically, enter and then exit the ppt animation, etc. In this issue, I will first share with you the specific steps of entering and then exiting the ppt animation. It is below. Friends, come and take a look. Look! 1. First, we open ppt on the computer, click outside the text box to select the text box (as shown in the red circle in the figure below). 2. Then, click [Animation] in the menu bar and select the [Erase] effect (as shown in the red circle in the figure). 3. Next, click [

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

After a two-year delay, the domestic 3D animated film 'Er Lang Shen: The Deep Sea Dragon' is scheduled to be released on July 13 After a two-year delay, the domestic 3D animated film 'Er Lang Shen: The Deep Sea Dragon' is scheduled to be released on July 13 Jan 26, 2024 am 09:42 AM

This website reported on January 26 that the domestic 3D animated film "Er Lang Shen: The Deep Sea Dragon" released a set of latest stills and officially announced that it will be released on July 13. It is understood that "Er Lang Shen: The Deep Sea Dragon" is produced by Mihuxing (Beijing) Animation Co., Ltd., Horgos Zhonghe Qiancheng Film Co., Ltd., Zhejiang Hengdian Film Co., Ltd., Zhejiang Gongying Film Co., Ltd., Chengdu The animated film produced by Tianhuo Technology Co., Ltd. and Huawen Image (Beijing) Film Co., Ltd. and directed by Wang Jun was originally scheduled to be released in mainland China on July 22, 2022. Synopsis of the plot of this site: After the Battle of the Conferred Gods, Jiang Ziya took the "Conferred Gods List" to divide the gods, and then the Conferred Gods List was sealed by the Heavenly Court under the deep sea of ​​Kyushu Secret Realm. In fact, in addition to conferring divine positions, there are also many powerful evil spirits sealed in the Conferred Gods List.

Hayao Miyazaki's animated film 'Porco Rosso' has been extended to January 16 next year, with a Douban score of 8.6 Hayao Miyazaki's animated film 'Porco Rosso' has been extended to January 16 next year, with a Douban score of 8.6 Dec 18, 2023 am 08:07 AM

According to news from this site, Miyazaki Hayao's animated film "Porco Rosso" has announced that it will extend the release date to January 16, 2024. This site previously reported that "Porco Rosso" has been launched in the National Art Federation Special Line Cinema on November 17, with a cumulative box office of over 2,000 10,000, with a Douban score of 8.6, and 85.8% of 4 and 5 star reviews. "Porco Rosso" was produced by Studio Ghibli and directed by Hayao Miyazaki. Moriyama Moriyama, Tokiko Kato, Otsuka Akio, Okamura Akemi and others participated in the dubbing. It was originally released in Japan in 1992. The film is adapted from Hayao Miyazaki's comic book "The Age of Airships" and tells the story of the Italian Air Force's ace pilot Pollock Rosen who was magically turned into a pig. After that, he became a bounty hunter, fighting against air robbers and protecting those around him. Plot synopsis: Rosen is a soldier in World War I

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

See all articles