带有 React 的动画按钮 Spring

Animated button with React Spring

我有 React-pose 背景,喜欢尝试 React-spring。我有一个非常简单的案例,我想将其与 React-spring 一起使用。

我有使用 React-pose 在 Codesanbox 中编写的案例,https://codesandbox.io/s/4wxzm60nk9

我试过自己转换它,但最终还是弄糊涂了。尤其是现在尝试用他们的钩子 API 来做的时候。我能得到的所有帮助都非常感谢。

谢谢。

我昨天刚做了一个动画按钮,所以我重构它来改变它的大小。

import React, {useState} from "react";
import { Spring, animated as a } from 'react-spring/renderprops';

const SpringButton = () => {
  const [pressed, setPressed] = useState(false);
  return (
  <Spring native from={{scale: 1}} to={{scale: pressed? 0.8 : 1}}>
    {({scale}) => (
      <a.button 
        style={{
          backgroundColor: 'red', 
          height: '100px', 
          width: '100px', 
          color: 'rgb(255, 255, 255)',
          transform: scale.interpolate(scale => `scale(${scale})`)
          }}
        onMouseDown={() => setPressed(true)}
        onClick={() => setPressed(false)}
        onMouseLeave={() => setPressed(false)}
      >
        Click me
      </a.button>
    )}
  </Spring>
  );
}

它还不是钩子接口,但我认为它可以帮助您理解它是如何工作的。它还使用更快的本机渲染。事件处理与 react-pose 有点不同。如果你想让动画真的有弹性,你也可以调整配置。

import {config} from 'react-spring/renderprops';
<Spring config={config.wobbly} ...>

https://codesandbox.io/s/7zlrkv4kjj

大概是这样的:https://codesandbox.io/s/pyvo8mn5x0

function App() {
  const [clicked, set] = useState(false)
  const { scale } = useSpring({ scale: clicked ? 0.8 : 1 })
  return (
    <div className="App">
      <animated.button
        onMouseDown={() => set(true)}
        onMouseUp={() => set(false)}
        style={{
          backgroundColor: 'red',
          height: '100px',
          width: '100px',
          color: '#FFF',
          transform: scale.interpolate(s => `scale(${s})`)
        }}
        children="Click me"
      />
    </div>
  )
}

如果你愿意,你也可以预先插入:

const props = useSpring({ transform: `scale(${clicked ? 0.8 : 1})` })
return <animated.button style={props} />

不像 pose react-spring 不包含手势内容,它为此选择与第 3 方库接口。例如:https://github.com/react-spring/react-with-gesture