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

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 可简单地使用useSpringanimated(.tag)/a(.tag)组件实现动画.

当使用函数作为参数时, 可使用api更灵活地操纵属性变化

import { useCallback, useMemo, useRef } from 'react'
import { useSpring, a } from '@react-spring/web'

const Demo = () => {
  const [props, api] = useSpring(() => ({ x: 0, y: 0 }))

  const demoRef = useRef<HTMLDivElement>(null)
  const getDemoOffset = useCallback(() => {
    return {
      x: demoRef.current?.offsetLeft ?? 0,
      y: demoRef.current?.offsetTop ?? 0,
    }
  }, [])

  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 --