react-nativeReactNative

React Native动画学习笔记

2017-06-11  本文已影响112人  瑾逸te

由于项目中需要加入几个小动画,于是研究了一下React Native的Animations。因为之前没有接触过有关动画的开发,包括使用CSS3制作动画的经验也不是太多,所以在看到设计图之后其实没有把握该如何入手。不过,在看了官方的文档和几篇博客之后,也实现了效果,其实也挺简单的,理解几个API之后开发就轻松不少。

官方文档中,有关动画的API有两个,一个是Animated,另一个是LayoutAnimation。其中,他们的区别是,Animated需要维护变量来实现动画,而LayoutAnimation则不需要变量,但是LayoutAnimation对于动画何时发生的控制不是非常自由,它的动画发生在下一次页面更新的时候(the next layout)。结合项目的需要,我使用了Animated。

Animated提供了三种动画类型,分别是:

那这些效果怎么用呢(下面以Animated.timing()为例)?

1. 在你的component内新建一个变量,比如this.animateValue
import React, {Animated} from 'react'

class AnimatedDemo extends React.Component {
  construct(props) {
    super(props)
    // 新建变量并且把默认值设置为0
    this.animatedValue = Animated.Value(0)
  }
}

2. 编写你的组件

注意,Animated默认有四个用于动画的组件(分别是Animated.Image, Animated.ScrollView, Animated.Text, Animated.View),当然,你也可以扩展自己的动画组件。

import React, {Animated} from 'react'

class AnimatedDemo extends React.Component {
  construct(props) {
    super(props)
    // 新建变量并且把默认值设置为0
    this.animatedValue = Animated.Value(0)
  }

  render() {
    return (
      <View style={}>
        <Animated.View style={{height: this.animatedValue, width: this.animatedValue, backgroundColor: "#00FFFF"}}>
        </Animated.View>
      </View>
    )
  }
}
3. 让组件动起来

现在,一切准备就绪了。下面,我们可以写非常简单的一个基于Animated.timing()的动画。

import React, {Animated} from 'react'

class AnimatedDemo extends React.Component {
  construct(props) {
    super(props)
    // 新建变量并且把默认值设置为0
    this.animatedValue = Animated.Value(0)
  }

componentDidMount() {
  Animated.timing(
    this.animatedValue,
    {
      toValue: 100,
      duration:1000
    }
  ).start();
}

  render() {
    return (
      <View style={}>
        <Animated.View style={{height: this.animatedValue, width: this.animatedValue, backgroundColor: "#00FFFF"}}>
        </Animated.View>
      </View>
    )
  }
}

这样,在component mount之后,动画就出现了。在Animated.timing()里面,你可以设置更多的参数来控制动画。

如果有多个动画需要完成,需要管理他们的开始时间等等,那么可以使用:

上一篇下一篇

猜你喜欢

热点阅读