前言
上一節(jié)中,介紹了React Native的LayoutAnimation慕爬。LayoutAnimation可以用來開發(fā)簡單的動畫窑眯。但面對組合動畫的開發(fā),就不那么方便了医窿。因此磅甩,在React Native中還有一個Animated來完成復(fù)雜動畫的開發(fā)。
Animated
Animated類似于一個單純的值動畫類姥卢。它本身并不完成任何動畫的功能實現(xiàn)卷要。我們通常將它設(shè)進state中。然后在合適的時機独榴,調(diào)用Animated.timing().start()
來開始執(zhí)行動畫僧叉。動畫本身,以參數(shù)的形式傳入timing
方法中棺榔。如下面的代碼所示:我們在創(chuàng)建Animated時瓶堕,傳入初始值為0。然后將timing中的動畫定義為目標(biāo)值為1症歇。時間設(shè)定為3000ms郎笆。
constructor(props){
super(props);
this.state={
fadeAnim: new Animated.Value(0),
};
}
// 在組件渲染完成之后執(zhí)行
componentDidMount(){
Animated.timing(
this.state.fadeAnim,{
toValue:1,
duration:3000,
}
).start();
}
將下來谭梗,我們只需要,將我們的某個ui與state中的fadeAnim關(guān)聯(lián)起來即可题画。
一個例子
創(chuàng)建一個在渲染時默辨,會漸進顯示的控件。漸進時間是3秒苍息,透明度由0到1缩幸。
import React ,{Component} from 'react';
import{
Animated,
} from 'react-native'
export default class FadeInView extends Component{
constructor(props){
super(props);
this.state={
fadeAnim: new Animated.Value(0),
};
}
// 在組件渲染完成之后執(zhí)行
componentDidMount(){
Animated.timing(
this.state.fadeAnim,{
toValue:1,
duration:3000,
}
).start();
}
render(){
return (
<Animated.View
style={{
...this.props.style,
opacity: this.state.fadeAnim, // 將透明度指定為動畫變量值
}}>
{this.props.children}
</Animated.View>
);
}
}
一些坑
在React Native Android中,需要做一些全局設(shè)置竞思。
const { UIManager } = NativeModules;
UIManager.setLayoutAnimationEnabledExperimental &&
UIManager.setLayoutAnimationEnabledExperimental(true);
參考資料:reactnative.cn表谊。
如有問題,歡迎指正盖喷。