React Spring特定键属性
在下面的代码中,我们将学习如何使用React Spring延迟更新属性。
React Spring 是一个简化UI元素动画的动画库。它基于弹簧物理学,可以实现自然的外观和感觉。它与其他动画库不同,其他动画库需要处理曲线、缓动和时间持续等。而React Spring可以自动同步这些参数。
平台: React Spring是一个跨平台的库,它支持React、React Native、Web和许多其他平台。它还支持所有的浏览器。
特定键属性: 它用于取消特定键的动画,您可以传递单个键、键数组或(key: string) => boolean函数。
语法:
useSpring({
cancel: //value
})
类型:
- 使用单个按键
cancel: 'x',
- 使用一个键数组
cancel: ['x', 'y'],
- 使用函数
cancel: key => key !== 'x',
使用React Spring创建应用程序的步骤:
步骤1: 使用以下命令创建一个新的应用程序。
npx create-react-app reactspringdemo
步骤2: 现在使用以下命令移动创建的项目文件夹。
cd reactspringdemo
步骤3: 安装react spring库。
npm install react-spring
项目结构: 看起来会像下面这样。
运行项目的步骤:
npm start
示例1: 在以下代码中,我们将使用上述语法来演示使用特定键属性的用法。在此示例中,我们使用了一个cancel函数来停止动画。
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<center>
<h1 style="color: green;">GeeksforGeeks</h1>
<h3>A computer science portal for geeks</h3>
<h2>React Spring Specific keys Props</h2>
<div id="root"></div>
</center>
</body>
</html>
GFG.jsx
import React from 'react';
import { useSpring, animated } from 'react-spring'
function LoopTrue() {
const styles = useSpring({
loop: true,
cancel: key => key !== 'x',
from: { rotateZ: 0 },
to: { rotateZ: 180 },
})
return (
<animated.div
style={{
width: 70,
height: 100,
backgroundColor: 'lightgreen',
...styles,
}}
/>
)
}
export default LoopTrue;
App.js
import React from 'react'
import GFG from './GFG'
function App() {
return (
<>
<GFG />
</>
);
}
export default App;
输出:
示例2: 在下面的代码中,我们将使用上述语法演示使用特定键道具的用法。在这个示例中,我们已经移除了特定的键。
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<center>
<h1 style="color: green;">GeeksforGeeks</h1>
<h3>A computer science portal for geeks</h3>
<h2>React Spring Specific keys Props</h2>
<div id="root"></div>
</center>
</body>
</html>
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: 70,
height: 100,
backgroundColor: 'lightgreen',
...styles,
}}
/>
)
}
export default LoopTrue;
App.js
import React from 'react'
import GFG from './GFG'
function App() {
return (
<>
<GFG />
</>
);
}
export default App;
输出:
参考: https://react-spring.dev/common/props#specific-keys