React Native填坑之旅–Button篇 React Native填坑之旅–动画 React Native填坑之旅–HTTP请求篇
动画是提高用户体验不可缺少的一个元素。恰如其分的动画可以让用户更明确的感知当前的操作是什么。
无疑在使用React Native开发应用的时候也需要动画。这就需要知道RN都给我们提供了那些动画,和每个动画可以处理的功能有哪些。
动画API提供了一些现成的组件:Animated.View,Animated.Text和Animated.Image默认支持动画。动画API会调用iOS或者Android的本地代码来完成这些组件的位移、大小等动画。这样各种动画在视觉上可以非常的流畅。
绕着屏幕转的动画:
<--< | | V--^解释一下: 1. 在this.state里用了Animated.ValueXY的实例。这样Animated动画就知道需要处理的是X和Y两个方向的值。 2. getStyle()方法会返回一个数组,因为动画需要square和transform两个样式值。getTranslateTransform()方法会获得一个数组:[{translateX: xValue}, {translateY: yValue}]。xValue和yValue就是根据我们开始的时候设置的Animated.ValueXY解析出来的。 3. 最后设置Animated.View。也就是动画最终作用的元素(或者叫做视图)。
依赖项:
import React from 'react'; import { Dimensions, StyleSheet, View, Animated } from 'react-native'; let { width, height } = Dimensions.get('window'); const SQUARE_DIMENSIONS = 30;样式:
const styles = StyleSheet.create({ container: { flex: 1 }, square: { width: SQUARE_DIMENSIONS, height: SQUARE_DIMENSIONS, backgroundColor: 'blue' } });我们准备让这个目标物体,一个方框,从左上角:x = 0, y = 0到左下角: x = 0, y = (screenHeight - squreHeight)。
const SPRING_CONFIG = {tension: 2, friction: 3}; componentDidMount() { Animated.spring(this.state.pan, { ...SPRING_CONFIG, toValue: {x: 0, y: height - SQUARE_DIMENSIONS} // return to start }).start(); }componentDidMount方法是RN组件的生命周期方法,在组件完成html渲染的时候调用。在组件渲染完成后开始动画。
我们指定了SPRING_CONFIG为弹簧动画的弹力和摩擦力,值都不大。所以这个方框会在屏幕的每个角稍微弹几下。
我们可以让几个动画按照顺序依次执行。这些动画会一个挨一个的执行。sequence方法是动画API组织动画的多种方式之一。也可以使用parallel来组织,这样几个动画会并行执行。
componentDidMount() { Animated.sequence([ Animated.spring(this.state.pan, { ...SPRING_CONFIG, toValue: {x: 0, y: height - SQUARE_DIMENSIONS} //animate to bottom left }), Animated.spring(this.state.pan, { ...SPRING_CONFIG, toValue: {x: width - SQUARE_DIMENSIONS, y: height - SQUARE_DIMENSIONS} // animated to bottom right }), Animated.spring(this.state.pan, { ...SPRING_CONFIG, toValue: {x: width - SQUARE_DIMENSIONS, y: 0} //animate to top right }), Animated.spring(this.state.pan, { ...SPRING_CONFIG, toValue: {x: 0, y: 0} // return to start }) ]).start(cb); }我们定义了四个弹簧动画。这个四个一组的动画执行的顺序就是前文指定的顺序。
调用动画的start方法的时候可以传入一个回调方法作为参数。这个回调方法会在这一组动画执行完成之后调用。在本例中,每次动画执行完之后会再次调用开始动画的方法。
componentDidMount() { this.startAndRepeat(); } startAndRepeat() { this.triggerAnimation(this.startAndRepeat); } triggerAnimation(cb) { Animated.sequence([ Animated.spring(this.state.pan, { ...SPRING_CONFIG, toValue: {x: 0, y: height - SQUARE_DIMENSIONS} //animate to bottom left }), Animated.spring(this.state.pan, { ...SPRING_CONFIG, toValue: {x: width - SQUARE_DIMENSIONS, y: height - SQUARE_DIMENSIONS} // animated to bottom right }), Animated.spring(this.state.pan, { ...SPRING_CONFIG, toValue: {x: width - SQUARE_DIMENSIONS, y: 0} //animate to top right }), Animated.spring(this.state.pan, { ...SPRING_CONFIG, toValue: {x: 0, y: 0} // return to start }) ]).start(cb); }调用triggerAnimation方法开始动画,并传入再次开始动画的方法startAndRepeat。
更多相关代码请移步:https://github.com/future-challenger/petshop/tree/master/client/petshop