useSpring 不会在道具更改时设置动画

useSpring won't animate on prop change

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

If you re-render the component with changed props, the animation will update.

我试过将道具作为 children 传递,但没有效果。我错过了什么?这是一个演示: 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>
    </>
  );
}

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

你可以做几件事。如果您添加重置 属性 那么它将在每个 re-render.

重复初始动画
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