代码之家  ›  专栏  ›  技术社区  ›  Martin Nordström

带React Spring的动画按钮

  •  0
  • Martin Nordström  · 技术社区  · 5 年前

    我来自一个反应姿势的背景,喜欢尝试反应弹簧。我有一个非常简单的案例,我想转移到使用反应弹簧。

    https://codesandbox.io/s/4wxzm60nk9

    我自己也试过改变,但最后弄糊涂了。尤其是现在使用hooks API时。我能得到的一切帮助都是非常感谢的。

    0 回复  |  直到 5 年前
        1
  •  3
  •   Peter Ambruzs    5 年前

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

    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>
      );
    }
    

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

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

        2
  •  4
  •   hpalu    5 年前

    可能是这样的: 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} />
    

    https://github.com/react-spring/react-with-gesture

    推荐文章