2

我来自 React-pose 背景,喜欢尝试 React-spring。我有一个非常简单的案例,我想将它转移到 React-spring 中使用。

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

我试过自己转换它,但我最终让自己感到困惑。尤其是现在尝试使用他们的 hooks API 来做这件事时。我能得到的所有帮助都非常感谢。

谢谢你。

4

2 回答 2

4

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

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

于 2019-03-13T08:14:52.587 回答
4

Something like this probably: 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>
  )
}

You could also interpolate up-front if you like:

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

Unlike pose react-spring does not include gesture stuff, it choses to interface with 3rd party libs for that. For instance: https://github.com/react-spring/react-with-gesture

于 2019-03-13T11:19:32.507 回答