【问题标题】:react-spring animation only working on click, not on hoverreact-spring 动画仅适用于点击,不适用于悬停
【发布时间】:2022-01-09 03:18:46
【问题描述】:

我有一个用 react-three-fiber 制作的基本旋转立方体,onPointerOver(也尝试过onPointerEnter)我想通过useSpring 将它平滑地旋转到起始位置。但是,当我悬停时它不仅不会这样做,而且只会这样做onClick。我有一个完全不同的函数来执行onClick——如果我禁用了那个道具,那么旋转重置就会完全失败。

我在Box 组件中有一个非常简单的设置:

export const Box = () => {
  const [active, setActive] = useState(false);
  const boxRef = useRef<Mesh>();

  const starterRotation = [0, 1, 1];

  useFrame(() => {
    if (boxRef.current) {
      boxRef.current.rotation.x += 0.01;
      boxRef.current.rotation.y -= 0.01;
    }
  });

  const [resetRotation, setSpring] = useSpring(() => ({
    rotation: starterRotation
  })); // trying to use the `set` syntax to call the useSpring and smoothly animate to a certain rotation.
  const springs = useSpring({ scale: active ? 1.5 : 1, config: config.wobbly });

  return (
    <animated.mesh
      // @ts-ignore
      rotation={resetRotation.rotation}
      scale={springs.scale}
      onClick={() => setActive(!active)}
      onPointerOver={() => setSpring.start()}
      ref={boxRef}
    >
      <boxGeometry args={[2, 1, 2]} />
      <meshStandardMaterial color="royalblue" />
    </animated.mesh>
  );
};

这是一个活生生的例子:https://codesandbox.io/s/react-spring-rotating-cube-np4v6

据我在他们的docs 中所说,这是正确的方法。我还看到一些关于它的 github 问题讨论,似乎有人担心 useSpring 解构的第二个参数不能正常工作,但轮换对我有用——只是触发事件不起作用。

【问题讨论】:

    标签: javascript reactjs animation react-spring react-three-fiber


    【解决方案1】:

    它确实有效,问题是您仍在根据 useFrame 调用中的 ref 更新 rotation,因此每帧都会更新。这将覆盖动画值。

    第二个问题是,如果您停止 useFramerotation 进行动画处理,它将无法工作,因为弹簧的内部值将设置为 [0,1,1],但这正是您希望它动画化的效果。

    这是使用 useSpringfromto 道具的好机会,我要做的是使用 ref 停止 useFrame 动画,然后使用 ref 获取当前值旋转在springSet.start 函数中用作from,然后to 这是您声明的starterRotation 值。

    你可以在这里看到它的效果——https://codesandbox.io/s/react-spring-rotating-cube-forked-1j02g?file=/src/components/Box.tsx

    【讨论】:

    • 这正是我想要的。谢谢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多