高效React Native动画开发 - LayoutAnimation

1,151 阅读3分钟
原文链接: www.jianshu.com

为什么要使用LayoutAnimtion🤔️

在我们平常的开发中,对于普通需求,经常会需要做一些简单的位移,淡入淡出等动画,而对于这种频繁的动画来说,使用Animated来做,虽然也是一个不错的选择,但是Animated在使用的过程中,需要更多的代码量,从定义变量,启动动画,结束,等等流程都要手动控制。如何高效快速地给App添加动画,也是一个比较广泛的需求。这就是我们使用LayoutAnimation的原因,快速,高效,相比Animated,虽然对于动画的控制减弱了,但是同时也获得了更高的开发效率。

和Animated有什么区别👀

上面说了LayoutAnimation对比Animated的优势,下面来更详细的对比一下两种方式在平常使用中的差异
首先是Animated(代码取自官方文档,并做了一些修改)

// part 1: 定义fadeAnim变量
state = {
    fadeAnim: new Animated.Value(0)
}

// part 2: 在某个时机启动动画(这个例子中我们在didMount生命周期中启动)
componentDidMount() {
  Animated.timing(
    this.state.fadeAnim,
    {
      toValue: 1,
      duration: 10000,
    }
  ).start();
}

// part 3: 在render中,使用Animated提供的Animated.View实现动画
render() {
  let { fadeAnim } = this.state;
  return (
    <Animated.View
      style={{
        opacity: fadeAnim,
      }}
    >
      {this.props.children}
    </Animated.View>
  );
}

下面是LayoutAnimation

// part 1: 使用普通的state来定义变量
state = {
    bottom: 0
}

// part 2: 
// 此处假设我们在某个View的style中,使用了this.state.bottom这个变量作为bottom的值
// 是的,只需要添加一行代码,你的View就有了动画!
LayoutAnimation.spring();
this.setState({ bottom: 20 });

通过上面的代码,我们可以很直观的发现LayoutAnimation有多方便,我们可以使用这个api以非常低的代价,使我们的App加入动画✌️

快速上手🏃‍♀️

React Native LayoutAnimation api提供了三个可以直接使用的api,分别是easeInEaseOut, linear, spring

LayoutAnimation.easeInEaseOut()
LayoutAnimation.linear()
LayoutAnimation.spring()

使用方式和上面的例子相同,只要在相应的setState之前调用下面三个API其中之一,在UI更新的时候,React Native就会自动让UI实现相应的动画效果。

进阶 - 自定义animation🎈🎈

为了自定义animation,我们就需要稍微深入的了解一下LayoutAnimation提供了哪些API了,首先,我们来看一下源码中接口的定义吧

/**
 * Automatically animates views to their new positions when the
 * next layout happens.
 *
 * A common way to use this API is to call it before calling `setState`.
 *
 * Note that in order to get this to work on **Android** you need to set the following flags via `UIManager`:
 *
 *     UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true);
 */
const LayoutAnimation = {
  /**
   * Schedules an animation to happen on the next layout.
   *
   * @param config Specifies animation properties:
   *
   *   - `duration` in milliseconds
   *   - `create`, `AnimationConfig` for animating in new views
   *   - `update`, `AnimationConfig` for animating views that have been updated
   *
   * @param onAnimationDidEnd Called when the animation finished.
   * Only supported on iOS.
   * @param onError Called on error. Only supported on iOS.
   */
  configureNext,
  /**
   * Helper for creating a config for `configureNext`.
   */
  create,
  Types: Object.freeze({
    spring: 'spring',
    linear: 'linear',
    easeInEaseOut: 'easeInEaseOut',
    easeIn: 'easeIn',
    easeOut: 'easeOut',
    keyboard: 'keyboard',
  }),
  Properties: Object.freeze({
    opacity: 'opacity',
    scaleX: 'scaleX',
    scaleY: 'scaleY',
    scaleXY: 'scaleXY',
  }),
  checkConfig(...args: Array<mixed>) {
    console.error('LayoutAnimation.checkConfig(...) has been disabled.');
  },
  Presets,
  easeInEaseOut: (configureNext.bind(null, Presets.easeInEaseOut): (
    onAnimationDidEnd?: any,
  ) => void),
  linear: (configureNext.bind(null, Presets.linear): (
    onAnimationDidEnd?: any,
  ) => void),
  spring: (configureNext.bind(null, Presets.spring): (
    onAnimationDidEnd?: any,
  ) => void),
};

主要方法🥩

  • configureNext
  • create

其实最主要的方法只有configureNext,create只是一个帮助创建配置的方法

使用configureNext

LayoutAnimation.configureNext(
  config: LayoutAnimationConfig,  // 提供一个动画的配置
  onAnimationDidEnd?: Function,  // 动画结束的回调,可以为空
)

从configureNext接口的定义中我们可以看到,使用很简单,提供一个LayoutAnimationConfig就可以了,那么这个LayoutAnimationConfig是什么呢

type LayoutAnimationConfig = $ReadOnly<{|
  duration: number,
  create?: AnimationConfig,
  update?: AnimationConfig,
  delete?: AnimationConfig,
|}>;

再次从定义中我们发现,这个config就是一个object,我们可以使用之前提到的create方法来快速生成它,下面是完整的使用例子

LayouteAnimation.configureNext(
  LayoutAnimation.create(
    // 动画的时长
    200,
    // 动画的类型, 例如linear,spring,easeIn
    LayouteAnimation.Types.linear,
    // 动画在哪些地方生效,scaleX就是在X轴生效
    LayouteAnimation.Properties.scaleX
  )
)

这样,我们就完全实现了LayoutAnimation动画的自定义了。更多的配置选项可以在源码中发现!