有时候我们需要一次新建多个动画,并让其同时运行。可以使用Animated.parallel方法同时启动一系列动画。比如要在屏幕上渲染一个欢迎界面,让界面同时显示两条欢迎信息和一个钱运登录按钮。可以创建三个独立的动画,然后对它们分别调用Animated.start方法,还有一种更有效的方法,使用Animated.parallel方法传入动画数组,然后同时运行动画。
下面我们将创建一个欢迎界面,该界面会显示两条信息和一个登录按钮。代码清单如下所示:
import React, { Component } from 'react'; import { StyleSheet, View, Animated, Text, TouchableHighlight } from 'react-native'; export default class RNAnimations extends Component { animatedTitle = new Animated.Value(-200); animatedSubtitle = new Animated.Value(600); animatedButton = new Animated.Value(800); componentDidMount() { this.animate(); } animate = () => { Animated.parallel([ Animated.timing( this.animatedTitle, { toValue: 200, duration: 800, } ), Animated.timing( this.animatedSubtitle, { toValue: 0, duration: 1400, delay: 800, } ), Animated.timing( this.animatedButton, { toValue: 0, duration: 1000, delay: 2200, } ) ]).start(); } render() { return ( <View style={styles.container}> <Animated.Text style={[styles.title, { marginTop: this.animatedTitle }]} > 欢迎</Animated.Text> <Animated.Text style={[styles.subTitle, { marginLeft: this.animatedSubtitle }]} > 一起开启新的征程吧! </Animated.Text> <Animated.View style={{ marginTop: this.animatedButton }}> <TouchableHighlight> <View style={styles.button}> <Text style={styles.text}>注册</Text> </View> </TouchableHighlight> </Animated.View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, margin: 16 }, title: { textAlign: 'center', fontSize: 24, marginBottom: 12, }, subTitle: { width: '100%', marginBottom: 24, textAlign: 'center', fontSize: 18, opacity: .8, }, button: { backgroundColor: '#008888', alignItems: 'center', padding: 10 }, text: { color: '#fff', fontSize: 20 } });
上述示例中,因为使用了Animated.parallel,所以三个动画会同时开始。在配置中添加了延迟属性delay,以控制其中两个动画的开始时间。效果如图所示:
使用(Chrome/Edge)在线运行。
React Native原生动画是不是比CSS动画酷一些呢?