Skip to content

Instantly share code, notes, and snippets.

@hpstuff
Created February 23, 2017 08:47
Show Gist options
  • Save hpstuff/78ef2a46c778642e104769736d483b77 to your computer and use it in GitHub Desktop.
Save hpstuff/78ef2a46c778642e104769736d483b77 to your computer and use it in GitHub Desktop.
React Native
'use strict';
import React from 'react';
import {
StyleSheet,
Text,
View,
Animated,
Easing
} from 'react-native';
export default class Score extends React.Component {
static defautlProps = {
score: 0
}
constructor(props) {
super(props);
this.dir = 1;
this.state = {
animation: new Animated.Value(0),
currentScore: 0,
oldScore: 0
};
}
startAnimation() {
Animated.timing(this.state.animation, {
toValue: 1,
duration: 300,
easing: Easing.inOut(Easing.quad)
}).start();
}
componentWillReceiveProps(nextProps) {
this.setState({
currentScore: nextProps.score,
oldScore: this.state.currentScore
});
this.state.animation.setValue(0);
this.dir = nextProps.score - this.state.currentScore;
}
componentDidUpdate() {
this.startAnimation();
}
render() {
const topAnimationStyle = {
transform: [{
translateY: this.state.animation.interpolate({
inputRange: [0, 1],
outputRange: [-20, this.dir >= 0 ? 0: -20]
})
}]
};
const currentAnimationStyle = {
transform: [{
translateY: this.state.animation.interpolate({
inputRange: [0, 1],
outputRange: [0, this.dir >= 0 ? 20: -20]
})
}]
};
const bottomAnimationStyle = {
transform: [{
translateY: this.state.animation.interpolate({
inputRange: [0, 1],
outputRange: [20, this.dir < 0 ? 0: 20]
})
}]
};
const topStyle = StyleSheet.flatten([styles.text, styles.textTop, topAnimationStyle]);
const currentStyle = StyleSheet.flatten([styles.text, styles.textCurrent, currentAnimationStyle]);
const bottomStyle = StyleSheet.flatten([styles.text, styles.textBottom, bottomAnimationStyle]);
return (
<View style={styles.container}>
<Animated.Text style={topStyle}>{this.state.currentScore}</Animated.Text>
<Animated.Text style={currentStyle}>{this.state.oldScore}</Animated.Text>
<Animated.Text style={bottomStyle}>{this.state.currentScore}</Animated.Text>
</View>
);
}
};
const styles = StyleSheet.create({
container: {
position: 'relative',
width: 25,
height: 20,
overflow: 'hidden'
},
text: {
position: 'absolute',
top: 0,
left: 0,
fontSize: 16,
paddingLeft: 5,
width: 25,
height: 20,
textAlign: 'right',
},
textBottom: {
transform: [{
translateY: 20
}]
},
textCurrent: {
transform: [{
translateY: 0
}]
},
textTop: {
transform: [{
translateY: -20
}]
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment