【问题标题】:What is the simplest way to animate `React.Component` with `react-spring` when prop is updated更新道具时使用“react-spring”为“React.Component”设置动画的最简单方法是什么
【发布时间】:2019-04-14 12:33:37
【问题描述】:

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

我找到了这个https://codesandbox.io/s/xpqq0ll5nw 并想用钩子实现同样的功能

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

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

【问题讨论】:

标签: reactjs react-spring


【解决方案1】:

你的 Counter 组件是正确的。这里的关键是“关键”属性。当 counter 改变时,它会在 1 和 0 之间交替。每次 key 改变时,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

【讨论】:

    猜你喜欢
    • 2015-05-31
    • 1970-01-01
    • 2019-07-10
    • 2023-03-17
    • 1970-01-01
    • 2011-01-14
    • 2020-05-20
    • 2013-04-06
    相关资源
    最近更新 更多