AnimationTing2.js
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Animated, Image, Easing } from 'react-native'; const IMG_URI = 'https://s3.amazonaws.com/media-p.slid.es/uploads/alexanderfarennikov/images/1198519/reactjs.png'; export default class AnimationTing2 extends Component { constructor(props) { super(props); //使用 ** Animated.Value** 声明了一个 spinValue 变量,并传了一个 0 作为初始值 this.animatedValue = new Animated.Value(0); } animate () { this.animatedValue.setValue(0);//this.spinValue 重置成 0 Animated.timing( this.animatedValue, { toValue: 1,//终值 duration: 4000,//一次动画的持续时间 easing: Easing.linear,//缓存函数 delay: 0 //延迟执行的时间 } ).start(() => this.animate()); //调用 start(),并将 this.spin 作为回调传递给 start,它将在(一次)动画完成之后调用,这也是创建无穷动画的一种基本方式 } componentDidMount() { this.animate(); // 开始执行动画 } render () { //inputRange 和 outputRange 参数给interpolate 方法,并分别赋值为 [0,1] 和 &[‘0deg’, ‘360deg’] 例 将数值 01 映射到了 0deg360deg //将这个值插入到 opacity、margins、text sizes 和 rotation 等样式属性中 //平移 没有返回 const marginLeft = this.animatedValue.interpolate({ inputRange: [0, 1], outputRange: [0, 300] }); //透明度渐变 const opacity = this.animatedValue.interpolate({ inputRange: [0, 0.5, 1], outputRange: [0, 1, 0] }); //平移 有返回 const movingMargin = this.animatedValue.interpolate({ inputRange: [0, 0.5, 1], outputRange: [0, 300, 0] }); //字体大小渐变 const textSize = this.animatedValue.interpolate({ inputRange: [0, 0.5, 1], outputRange: [8, 32, 8] }); //沿x旋转 const rotateX = this.animatedValue.interpolate({ inputRange: [0, 0.5, 1], outputRange: ['0deg', '180deg', '0deg'] }); return ( <View style={styles.container}> <Animated.View style={{ marginLeft, height: 30, width: 40, backgroundColor: 'red'}} /> <Animated.View style={{ opacity, marginTop: 10, height: 30, width: 40, backgroundColor: 'blue'}} /> <Animated.View style={{ marginLeft: movingMargin, marginTop: 10, height: 30, width: 40, backgroundColor: 'orange'}} /> <Animated.Text style={{ fontSize: textSize, height: 50, width: 400, marginTop: 10, color: 'green'}} > Animated Text! </Animated.Text> <View></View> <Animated.View style={{ transform: [{rotateX}], marginTop: 50, height: 100, width: 100, backgroundColor: 'black'}}> <Text style={{color: 'white'}}>Hello from TransformX</Text> </Animated.View> <View></View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 150, marginLeft: 10, } });使用:
import React from 'react'; import { AppRegistry, View, Text, StyleSheet, Animated, } from 'react-native'; import AnimationTing2 from './AnimationTing2'; class MyFirstProject extends React.Component{ render() { return ( <View> <AnimationTing2></AnimationTing2> </View> ); } } AppRegistry.registerComponent('MyFirstProject', ()=> MyFirstProject);