React Spring的From属性
在本篇文章中,我们将学习如何使用React Spring的From属性。 React Spring 是一个使动画UI元素简单化的动画库。它基于弹簧物理学,可帮助实现自然的外观和感觉。与其他动画库不同,其他库需要处理曲线、缓动和时间持续等,而React Spring的所有情况都是同步的。
平台: React Spring是一个跨平台库,支持react、react-native、web和许多其他平台。它还支持所有的浏览器。
From属性: 用于定义动画的初始点。
语法:
from: { initial point }
创建React应用的步骤如下:
步骤1: 使用以下命令创建一个新应用程序。
npx create-react-app reactspringdemo
步骤2: 现在使用以下命令移动创建的项目文件夹。
cd reactspringdemo
步骤3: 安装react spring库。
npm install react-spring
示例1: 在下面的代码中,我们将使用上述语法来示范使用From属性。
GFG.jsx
import { useSpring, animated } from 'react-spring'
function FromProp() {
const styles = useSpring({
loop: true,
from: { rotateZ: 0 },
to: { rotateZ: 180 },
})
return (
<animated.div
style={{
width: 80,
height: 80,
backgroundColor: 'lightgreen',
borderRadius: 100,
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 FromProp;
App.js
import React from 'react'
import GFG from './GFG'
function App() {
console.log('hello')
return (
<>
<GFG />
</>
);
}
export default App;
运行应用程序的步骤:
打开终端并输入以下命令。
npm start
输出:
示例2: 在下面的代码中,我们将使用上述语法来演示使用From prop的用法。在第一个示例中,它是从0到180的移动,在这个示例中,它是循环的。
GFG.jsx
import { useSpring, animated } from 'react-spring'
function FromProp() {
const styles = useSpring({
from: { x: 0 },
config: { duration: 1000 },
loop: {
x: 100,
},
})
return (
<animated.div
style={{
width: 80,
height: 80,
backgroundColor: 'lightgreen',
borderRadius: 100,
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 FromProp;
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/imperatives-and-refs#the-from-prop