啥也不说,上代码
动画组件
import React from 'react';
import {
Animated, View, StyleSheet,
findNodeHandle,
UIManager
} from 'react-native';
interface Props {
// 如果标识值不同,组件将执行动画
sign: string
}
export default class TransitionAnimation extends React.Component<Props> {
// 声明一个动画值
fadeAnim = new Animated.Value(500);
ref = undefined;
width = 0;
height = 0;
state = {
showChildren: this.props.children,
animationing: false
}
shouldComponentUpdate(nextProps, nextState, context) {
if (this.props.sign != nextProps.sign) {
this.fadeAnim.setValue(this.height);
this.setState({ animationing: true }, () => {
// 执行动画
Animated.timing(
// 动画值
this.fadeAnim,
{
toValue: 0,
duration: 300, // 让动画持续一段时间,10s
} as Animated.TimingAnimationConfig
).start(({ finished }) => {
if (finished) {
this.setState({ showChildren: nextProps.children, animationing: false });
}
});
});
}
return true;
}
render() {
return (
<View onLayout={(e) => {
this.height = e.nativeEvent.layout.height;
this.width = e.nativeEvent.layout.width;
}} style={styles.view} ref={r => this.ref = r}>
{this.state.showChildren}
<Animated.View // 使用专门的可动画化的View组件
style={[styles.animatedView, { height: this.state.animationing ? '100%' : 0, top: this.fadeAnim }]}
>
{this.state.animationing && this.props.children}
</Animated.View>
</View>
);
}
}
const styles = StyleSheet.create({
view: {
width: '100%',
height: '100%',
},
animatedView: {
width: '100%',
position: 'absolute',
}
});
使用实例
<TransitionAnimation
sign={this.props.history.location.pathname}
>
<Switch location={this.props.location}>
<Route path='/Home' component={Component1} />
<Route path='/Account' component={Component2} />
</Switch>
</TransitionAnimation>