React Spring Imperatives & Refs
在本文中,我们将学习 Imperatives 和 Refs 的工作原理。
React spring 是一个使动画化 UI 元素变得简单的动画库。它基于弹簧物理学,可以实现自然的外观和感觉。它与其他动画库不同,在其他动画库中,用户必须处理曲线、缓动和时间持续等,而这些都是同步的。
平台: React spring 是一个跨平台库,支持 react、react-native、web 和其他许多平台。它也支持所有浏览器。
Imperatives 和 Refs: Imperatives 是一小组属性,而 Refs 用于返回可变的 ref 对象。
Imperative API 的语法:
api({
//property
})
Refs的语法:
useSpringRef()
创建React应用的步骤:
步骤1: 使用以下命令创建一个新的应用程序。
npx create-react-app reactspringdemo
步骤2: 现在使用以下命令移动已创建的项目文件夹。
cd reactspringdemo
步骤3: 安装react spring库。
npm install react-spring
项目结构: 它将看起来如下所示。
示例1: 在下面的代码中,我们将利用上述语法来演示使用命令式API的方法。
GFG.jsx
import { useSpring, animated } from 'react-spring'
import React, { useEffect } from 'react';
function BackwardsCompatability() {
const [styles, api] = useSpring(() => ({
from: { x: -50, opacity: 1 },
}))
useEffect(() => {
api({
x: 150,
opacity: 1,
loop: { reverse: true },
})
})
return (
<animated.div
style={{
width: 80,
height: 80,
backgroundColor: 'lightgreen',
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 BackwardsCompatability;
App.js
import React from 'react'
import GFG from './GFG'
function App() {
console.log('hello')
return (
<>
<GFG />
</>
);
}
export default App;
运行应用程序的步骤: 运行以下命令:
npm start
输出:
示例2: 在下面的代码中,我们将使用上述语法来演示使用 Refs。
GFG.jsx
import { useSpring, animated } from 'react-spring'
import React, { useEffect } from 'react';
function BackwardsCompatability() {
const [styles, api] = useSpring(() => ({
from: { x: -50, opacity: 1 },
}))
useEffect(() => {
api({
x: 150,
opacity: 1,
loop: true,
})
})
return (
<animated.div
style={{
width: 80,
height: 80,
backgroundColor: 'lightgreen',
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 BackwardsCompatability;
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#imperative-api