React Spring 事件作为对象

React Spring 事件作为对象

在本文中,我们将学习如何使用 React Spring 将事件作为对象使用。 React Spring 是一个使动画化 UI 元素变得简单的动画库。它基于弹簧物理学,帮助实现自然的外观和感觉。与其他动画库不同,它不需要处理曲线、缓动和持续时间,所有这些都是互相同步的。

平台支持: React Spring 是一个跨平台库,支持 react、react-native、web,以及许多其他平台。它还支持所有浏览器。

事件作为对象: 它用于创建具有 onRest 等事件的对象。

语法:

useSpring({
    from: { x: 0, y: 0 },
    onRest: {
        x: () => console.log('x.onRest'),
        y: () => console.log('y.onRest'),
    },
})

在react中创建一个应用程序的步骤。

步骤1: 使用以下命令创建一个新的应用程序。

npx create-react-app reactspringdemo

步骤2: 现在使用以下命令移动已创建的项目文件夹。

cd reactspringdemo

步骤3: 安装react spring库。

npm install react-spring

项目结构: 将app文件夹导入应用程序,之后项目结构将如下所示。

React Spring 事件作为对象

示例1: 在下面的代码中,我们将利用上述语法来演示将事件作为对象使用的用法。

  • GFG.jsx
import React from 'react'; 
import { useSpring, animated } from 'react-spring'
  
function OnRest() { 
    const styles = 
        useSpring({ 
            from: { x: 0, y: 0 }, 
            onRest: { 
                x: () => console.log('x.onRest'), 
                y: () => console.log('y.onRest'), 
            }, 
        }) 
  
    return ( 
        <animated.div 
            style={{ 
                width: 80, 
                margin: 221, 
                height: 80, 
                backgroundColor: 'green', 
                borderRadius: 16, 
                ...styles, 
            }} 
        /> 
    ) 
} 
export default OnRest; 
  • App.js
import React from 'react'
import GFG from './GFG'
  
function App() { 
    console.log('hello') 
    return ( 
        <> 
            <GFG /> 
        </> 
    ); 
} 
  
export default App; 

运行该应用的步骤:

打开终端并输入以下命令。

npm start

输出:

React Spring 事件作为对象

  • GFG.jsx
import React from 'react'; 
import { useSpring, animated } from 'react-spring'
  
  
function LoopTrue() { 
    const styles = useSpring({ 
        loop: true, 
        from: { rotateZ: 0 }, 
        to: { rotateZ: 180 }, 
  
    }) 
  
    return ( 
        <animated.div 
            style={{ 
                width: 80, 
                height: 80, 
                backgroundColor: 'green', 
                borderRadius: 16, 
                margin: 100, 
                ...styles, 
            }} 
        /> 
    ) 
} 
export default LoopTrue; 
  • App.js
import React from 'react'
import GFG from './GFG'
  
function App() { 
    console.log('hello') 
    return ( 
        <> 
            <GFG /> 
        </> 
    ); 
} 
  
export default App;

运行应用程序的步骤: 打开终端并输入以下命令:

npm start

输出:

React Spring 事件作为对象

参考: https://react-spring.dev/common/props#events-as-functions

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程