【问题标题】:Animated button with React Spring带有 React Spring 的动画按钮
【发布时间】:2019-08-03 10:51:54
【问题描述】:

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

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

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

谢谢。

【问题讨论】:

    标签: react-spring


    【解决方案1】:

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

    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

    【讨论】:

    • 哇!非常感谢彼得!稍后将尝试使其成为钩子。我还注意到一件事,当你按住一个姿势动画按钮并将鼠标拖离按钮时,它仍然“被点击”,同时如果你对 react-spring 按钮做同样的事情,它会回到原来的状态形式。您认为这与这两个库的构建方式有关吗?再次感谢您的回答。现在我可以从我的项目中删除 react-pose 哈哈
    • 这就是我解决事件处理的方法。 Pose 处理按钮外的鼠标向上事件。我不想摆弄它,所以我使用 mouseLeave 事件重置为原始状态。使用 react-spring,所有事件处理都取决于您的实现。
    • 我明白了。好吧,对于我的用例来说,这并不重要,但看看他们如何处理它会很有趣。再次感谢
    【解决方案2】:

    大概是这样的: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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2013-07-26
      相关资源
      最近更新 更多