我们在平时进行Native开发的时候,为了更好的用户体验,我们会做一些动画效果,而在React Native中也提供了相应的动画API。
RN主要的动画分为两大类:
- LayoutAnimation用来实现布局切换的动画。
- Animated更加精确的交互式的动画
LayoutAnimation
LayoutAnimation是在布局发生变化时触发动画的接口,这意味着你需要通过修改布局(比如修改了组件的style,插入新的组件)来触发动画。
该接口常用的方法是 LayoutAnimation.configureNext(conf<Object>),用来设置下次布局变化时的动画效果,需要在执行setState前调用。
相关配置:
static configureNext(config:Config,onAnimationDidEnd?:Function)
计划下一次布局要发生的动画
@param config 动画相应属性的配置:
{
duration: 700, //动画持续的时间,单位是毫秒
create: { //配置创建新视图的动画
type: 'linear', //线性模式
property: 'opacity' //动画属性,除了opacity还有一个scaleXY可以配置
},
update: { //配置更新视图时的动画
type: 'spring', //弹跳模式
springDamping: 0.4 //弹跳阻尼系数
}
}
@param onAnimationDidEnd 当动画结束的时候被调用,只在IOS设备上支持。
@param onErr 当动画产生错误的时候被调用,只有在IOS设备上支持。
其中动画type的类型可枚举为:
spring //弹跳
linear //线性
easeInEaseOut //缓入缓出
easeIn //缓入
easeOut //缓出
keyboard //键入
要注意的是在安卓平台使用LayoutAnimation动画必须加上这么一句代码,否则动画会失效
UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true);
示例:
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
Dimensions,
LayoutAnimation,
} from 'react-native';
var screenW = Dimensions.get('window').width;
var screenH = Dimensions.get('window').height;
export default class extends Component {
constructor(props) {
super(props)
this.state = {
width: 100,
height: 150,
left:20,
top:20,
}
}
_clickStartAnimation() {
LayoutAnimation.configureNext({
duration: 1000, //持续时间
create: {
type: LayoutAnimation.Types.spring,
property: 'opacity',
},
update: {
type: 'spring',
springDamping: 0.4,
}
});
this.setState({
width: this.state.width + 40,
height: this.state.height + 60,
left: this.state.left + 20,
top: this.state.top + 50,
});
}
render(){
return (
<View style={styles.mainStyle