当 prop 更新时,使用 `react-spring` 为 `React.Component` 设置动画的最简单方法是什么

What is the simplest way to animate `React.Component` with `react-spring` when prop is updated

如何使用 react-spring 库对 React 组件进行动画处理取决于 props 更新

我找到了这个 https://codesandbox.io/s/xpqq0ll5nw 并且想用 hooks 实现同样的东西

const Counter = ({quantity}) => {
  const animation = useSpring({
    transform: 'scale(1)',
    from: { transform: 'scale(1.2)' },
  });

  return (
    <animated.span style={animation}">
      {quantity}
    </animated.span>
  )
}

您的 Counter 组件是正确的。这里的关键是 'key' 属性。当计数器改变时,它在 1 和 0 之间交替。每次键改变时,React 都会分配一个新的 Counter 组件实例,而不是旧的,重复 Counter 组件的初始动画。

  class App extends Component {
    state = { count: 0 };
    increment = () => this.setState({ count: this.state.count + 1 });
    render() {
      return (
        <Fragment>
          <button onClick={this.increment}>Update!</button>
          <Counter key={this.state.count % 2} quantity={this.state.count} />
        </Fragment>
      );
    }
  }

这里是整个例子:https://codesandbox.io/s/jjyp6p0yl9