React Spring 命令式更新
在本文中,我们将学习如何使用 React Spring 进行命令式更新。 React Spring 是一个使 UI 元素动态变化变得简单的动画库。它基于弹簧物理模型,使得动画具有自然的外观和感觉。与其他动画库不同的是,React Spring 可以自动处理曲线、缓动和持续时间,使它们保持同步。
平台: React Spring 是一个跨平台库,支持 React、React Native、Web 等多个平台。它也支持所有浏览器。
命令式更新: 命令式更新可以用来将默认属性设置为 true。
语法:
useSpring({
from: { x: ... },
to: async animate => {
// The `config` prop below is inherited by
// both objects in the `to` array.
await animate({
to: [{ x: ... }, { x: ... }],
config: { tension: ... },
})
},
})
创建React应用的步骤。
步骤1: 使用以下命令创建一个新的应用程序。
npx create-react-app reactspringdemo
步骤2: 现在使用以下命令移动已创建的项目文件夹。
cd reactspringdemo
步骤3: 安装 react spring 库。
npm install react-spring
项目结构: 将app文件夹导入应用程序,之后项目的结构将如下所示。
示例1: 在下面的代码中,我们将利用上面的语法来演示命令式更新的使用方法。
GFG.jsx
import React from 'react';
import { useSpring, animated } from 'react-spring'
function OnRest() {
const styles = useSpring({
from: { x: 0 },
to: async animate => {
// The `config` prop below is inherited by
// both objects in the `to` array.
await animate({
to: [{ x: 100 }, { x: 0 }],
config: { tension: 100 },
})
},
})
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
输出:
示例2: 在下面的代码中,我们将使用上述语法来演示命令式更新的使用。在这个示例中,我们已经移除了紧张感。
GFG.jsx
import React from 'react';
import { useSpring, animated } from 'react-spring'
function GfG() {
const styles = useSpring({
from: { x: 0 },
to: async animate => {
// The `config` prop below is inherited by
// both objects in the `to` array.
await animate({
to: [{ x: 0 }, { y: 500 }],
})
},
})
return (
<animated.div
style={{
width: 80,
height: 80,
backgroundColor: 'green',
borderRadius: 50,
boxShadow: 'rgb(0,0,0,0.44) 0px 5px 5px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'green',
margin: 250,
...styles,
}}
/>
)
}
export default GfG;
App.js
import React from 'react'
import GFG from './GFG'
function App() {
console.log('hello')
return (
<>
<GFG />
</>
);
}
export default App;
运行应用程序的步骤: 打开终端并输入以下命令。
npm start
输出:
参考资料: https://react-spring.dev/common/props#imperative-updates