React 动画库: react-spring 简单使用

Hello
const Demo = () => {
const props = useSpring({
from: { opacity: 0 },
to: { opacity: 1 },
loop: {
reverse: true,
},
})
return (
<div className="demo">
<a.div style={props}>Hello</a.div>
</div>
)
}
如上代码, react-spring 可简单地使用useSpring
和animated(.tag)/a(.tag)
组件实现动画.
当使用函数作为参数时, 可使用
api
更灵活地操纵属性变化
// mdx的 esbuild 不支持 type system, 有点尴尬? 好多ignore
import { useCallback, useMemo, useRef } from 'react'
import { useSpring, a } from 'react-spring'
const Demo = () => {
const [props, api] = useSpring(() => ({ x: 0, y: 0 }))
// @ts-ignore
const demoRef = useRef(null)
const getDemoOffset = useCallback(() => {
return {
// @ts-ignore
x: demoRef.current.offsetLeft,
// @ts-ignore
y: demoRef.current.offsetTop,
}
}, [])
const moveTo = useCallback((e) => {
const demoOffset = getDemoOffset()
api.start({
x: e.pageX - demoOffset.x,
y: e.pageY - demoOffset.y,
config: { mass: 5, tension: 1000, friction: 60 },
})
}, [])
return (
<div
className="demo"
style={{
height: 300,
cursor: 'move',
}}
onMouseMove={(e) => moveTo(e)}
ref={demoRef}
>
<a.div style={props}>Move anywhere</a.div>
</div>
)
}
export default Demo
Move anywhere
具体 api 在官网上太详细了.
其实只是想测试一下mdx
各样式/组件/图床收录情况.
-- Fin --