最近在使用react native進行App混合開發,相對於H5的開發,RN所提供的樣式表較少,RN中不能使用類似於css3中的動畫,因此,RN提供了Animated的API
1.寫一個最簡單的動畫
import React, { Component } from 'react'
import { Animated, Text, View } from 'react-native'
Class DropList extends React.Component {
constructor(props) {
suoer(props)
this.state = {
showMenu: false,
transVal: new Animated.value(0)
}
this.switchMenu = this.switchMenu.bind(this)
}
// 菜單展開動畫
stratAni() {
Animated.timing(
this.state.fadeAnim,
{
toValue: 50,
duration: 500,
useNativeDriver: true // <-- 加上這一行 是否啟用原生動畫
// 啟用后,動畫一開始就完全脫離了 JS 線程,因此此時即便 JS 線程被卡住,也不會影響到動畫了
// 動畫值在不同的驅動方式之間是不能兼容的。因此如果你在某個動畫中啟用了原生驅動,那么所有和此動畫依賴相同動畫值的其他動畫也必須啟用原生驅動
// 啟用原生動畫后,僅支持opacity和transform屬性變化
}
).start()
}
// 菜單收起動畫
closeAni() {
Animated.timing(
this.state.menuTransform,
{
toValue: 0,
duration: 0,
useNativeDriver: true
}
).start()
}
// 菜單展開與折疊
switchMenu() {
if (this.state.showMenu) { // 收起
this.setState({
showMenu: false
})
this.closeAni()
} else { // 折疊
this.setState({
showMenu: true
})
this.stratAni()
}
}
render() {
let {
showMenu,
transVal
} = this.state
return(
<View>
<Text onPRess={this.switchMenu}>Switch Menu</Text>
<Animated.View style={{ height: 50, backgroundColor: 'red', position: 'absolute', top: -50, transform: [ translateY: transVal ] }}>
</Animated.View>
</View>
)
}
}
2.插值動畫(loading旋轉動畫)
this.state = {
aniVal: new Animated.Value(0)
}
this.aniVal = 0
componentDidMount() {
this.state.aniVal.setValue(0);
Animated.timing(this.state.aniVal, {
toValue: 1,
duration: 200
}).start();
}
<Animated.View
style={{
transform: [
{
translateY: this.state.aniVal.interpolate({
inputRange: [0, 1],
outputRange: [100, 0]
})
}
],
opacity:this.state.aniVal.interpolate({
inputRange: [0, 1],
outputRange: [0.2, 1]
})
}}>
<Text>加載中...</Text>
</Animated.View>
