【问题标题】:useSpring won't animate on prop changeuseSpring 不会在道具更改时设置动画
【发布时间】:2021-01-06 03:16:12
【问题描述】:

与 Spring 文档中提到的相反,useSpring 不会在道具更改时为我的计数器组件设置动画:

如果您使用更改的道具重新渲染组件,动画将更新。

我尝试将道具作为孩子传递,但没有效果。我错过了什么?这是一个演示: https://codesandbox.io/s/spring-counter-jsylq?file=/src/App.js:199-230

import React, { useState } from "react";
import { animated, useSpring } from "react-spring";

const Counter = ({ value }) => {
  const anim = useSpring({ from: { opacity: 0 }, to: { opacity: 1 } });

  return <animated.h1 style={anim}>{value}</animated.h1>;
};

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <>
      <Counter value={count} />
      <button onClick={() => setCount(count + 1)}>increment</button>
    </>
  );
}

【问题讨论】:

    标签: reactjs react-spring


    【解决方案1】:

    它只是说动画会更新。但现在动画有点静态。

    你可以做几件事。如果添加了 reset 属性,那么它将在每次重新渲染时重复初始动画。

    const anim = useSpring({ from: { opacity: 0 }, to: { opacity: 1 } , reset: true});
    

    或者您可以根据计数值添加一些属性。例如平价。奇数变为蓝色,偶数变为红色。

    const anim = useSpring({ from: { opacity: 0 }, to: { opacity: 1 , color: value % 2 === 0 ? 'red' : 'blue'} });
    

    你怎么看?

    https://codesandbox.io/s/spring-counter-forked-znnqk

    【讨论】:

    • 重置属性为我做了。天哪,我不敢相信我还没有遇到过。谢谢。
    • 这可行,但它会在任何状态更改时重新运行动画。有没有办法选择哪个更改? (如 useEffect 依赖项)
    • @Elron 您可以为重置创建一个变量,并且您可以根据需要更新此变量。即使在 useEffect 钩子中。
    • 怎么样? reset: variableName ?
    猜你喜欢
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    相关资源
    最近更新 更多