前言
React Native作為大前端開發的一種技術,自然離不開各種炫酷的動效。在React Native中動效有兩種實現的方式。它們分別為:** LayoutAnimation、 Animated**。
今天,我們給一個LayoutAnimation的例子。LayoutAnimation適合開發相對簡單的動畫。如,一個界面的出現,或一個按鈕做一些簡單的縮放動畫。
一個例子
需求
創建一個<Text>,每次點擊它時,它就會以動畫的形式變大(長寬各增加50像素)。動畫持續時間5s。具有一定的彈性。
code
import React, { Component } from 'react';
import {
NativeModules,
LayoutAnimation,
AppRegistry,
View,
Text,
TouchableOpacity,
} from 'react-native';
import ListViewBisc from '../AwesomeProject/App/widget/ListViewBisc'
import HttpClient from '../AwesomeProject/App/widget/HttpClient'
const { UIManager } = NativeModules;
UIManager.setLayoutAnimationEnabledExperimental &&
UIManager.setLayoutAnimationEnabledExperimental(true);
class HelloWorld extends Component {
constructor(props) {
super(props);
this.state={
w:100,
h:50
};
}
_onPress = () => {
// Animate the update
LayoutAnimation.configureNext(LayoutAnimation.create(5000,
LayoutAnimation.Types.spring,
LayoutAnimation.Properties.scaleXY));
this.setState({w: this.state.w + 50, h: this.state.h + 50})
}
render(){
return (
<TouchableOpacity onPress = {this._onPress}>
<Text style={{width: this.state.w, height: this.state.h , backgroundColor:'#f0f0f0'}}>Press me!</Text>
</TouchableOpacity>
)
}
}
我們用一個TouchableOpacity包裹了<Text>控件。然后,給TouchableOpacity輸入按壓回調,在回調中調用動畫。
我們使用LayoutAnimation創建動畫,輸入了三個參數,分別是動畫時間5000ms、插值器類型彈性和動畫類型縮放。
然后我們就可以直接改變state中的值,以調用render重新渲染界面。
總結
利用LayoutAnimation我們可以創造簡單的動畫。可以控制簡單的時間,插值類型,動畫類型。而如果需要更為精確復雜的控制,我們則需要用到Animted。
如有問題,歡迎指正。