React Spring属性概述
在本文中,我们将学习React Spring中属性的概述。React Spring是一个使UI元素动画化变得简单的动画库。
React Spring 基于弹簧物理学,可以实现自然的外观和触感。它不同于其他动画库,其他动画库需要处理曲线、缓动和持续时间,而这些属性都是同步的。
平台: React Spring是一个跨平台库,支持React、React Native、Web和多个其他平台。它还支持所有浏览器。
属性: 属性是一个对象,在其中执行某些循环动画。
在属性中使用的属性如下:
属性名称 | 类型 | 描述 |
---|---|---|
from | obj | 此属性是动画的初始点。 |
to | obj/fn/array(obj) | 此属性是动画的最终点。 |
loop | obj/fn/bool | 如果将此属性值设置为true,则循环将运行。 |
delay | number/fn | 此属性用于定义动画的延迟。 |
immediate | bool/fn | 此属性用于定义动画的immediate属性。 |
config | obj/fn | 此属性用于定义动画的config。 |
reset | bool | 此属性用于定义动画的reset属性。 |
reverse | bool | 此属性用于定义动画的reverse属性。 |
cancel | bool/string/fn | 此属性用于设置动画的cancel属性。如果设置为true,则会停止动画。 |
pause | bool | 此属性用于设置动画的pause属性。如果设置为true,则会暂停动画。 |
events | fn | 此属性用于定义动画的事件。 |
创建 React 应用的步骤如下:
步骤1: 使用以下命令创建新应用程序。
npx create-react-app reactspringdemo
步骤2: 现在使用以下命令移动创建的项目文件夹。
cd reactspringdemo
步骤3: 安装 React Spring 库。
npm install react-spring
项目结构: 它将如下所示。
示例1: 在下面的代码中,我们将学习关于使用上述语法的prop。
GFG.jsx
import React from 'react';
import { useSpring, animated } from 'react-spring'
const LoopingCard = () => {
/**
* Define the style for the animation
* using the useSpring hook
*/
const styles = useSpring({
loop: true,
from: { rotateZ: 0 },
to: { rotateZ: 360 },
duration: 2000,
});
/**
* Animated div is the extended version of div that
* accepts the properties defined above.
*/
return (<animated.div
style={{
width: 80,
height: 80,
backgroundColor: 'd6d6d6',
borderRadius: 16,
boxShadow: 'rgb(0,0,0,0.44) 0px 5px 5px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'green',
margin: 250,
...styles,
}} >GFG</animated.div>
);
}
export default LoopingCard;
App.js
import React from 'react'
import GFG from './GFG'
function App() {
console.log('hello')
return (
<>
<GFG />
</>
);
}
export default App;
运行应用程序的步骤: 在终端中写下面的代码来运行应用程序:
npm start
输出:
示例2: 在下面的代码中,我们将使用上述语法来学习prop。
GFG.jsx
import React from 'react';
import { useSpring, animated } from 'react-spring'
const LoopingCard = () => {
/**
* Define the style for the animation
* using the useSpring hook
*/
const styles = useSpring({
loop: true,
cancel: true,
from: { rotateZ: 0 },
to: { rotateZ: 360 },
duration: 2000,
});
/**
* Animated div is the extended version of div that
* accepts the properties defined above.
*/
return (<animated.div
style={{
width: 80,
height: 80,
backgroundColor: 'd6d6d6',
borderRadius: 16,
boxShadow: 'rgb(0,0,0,0.44) 0px 5px 5px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'green',
margin: 250,
...styles,
}} >GFG</animated.div>
);
}
export default LoopingCard;
App.js
import React from 'react'
import GFG from './GFG'
function App() {
console.log('hello')
return (
<>
<GFG />
</>
);
}
export default App;
输出:
参考: https://react-spring.dev/common/props#overview