我建议您阅读更多有关插值法 https://facebook.github.io/react-native/docs/animations.html#interpolation因为在 React Native 中做几乎任何类型的动画时它都非常有用。
基本上与interpolate
您可以将一些动画值映射到其他值。在您的情况下,您想要将 40-100 之间的数字映射到百分比字符串,例如50%
。您要做的第二件事是将 40-100 之间的数字映射到从(例如)红色到蓝色的颜色。
完整阅读 interpolate 文档并进行实验,然后询问您是否有疑问:)
所以我会这样做:
class AnimatedButton extends Component {
constructor(props) {
super(props);
this.state = { width: new Animated.Value(100) };
}
toggleWidth() {
const endWidth = this.props.isFullWidth ? 40 : 100;
Animated.timing(this.state.width, {
toValue: endWidth,
duration: 200,
easing: Easing.linear,
}).start();
}
render() {
<TouchableOpacity
style={{
width: this.state.width.interpolate({
inputRange: [0, 1],
outputRange: ['0%', '100%'],
}),
backgroundColor: this.state.width.interpolate({
inputRange: [40, 100],
outputRange: ['rgba(30, 70, 30, 1.0)', 'rgba(220, 100, 50, 0.8)'],
}),
}}
onPress={this.props.onPress}
>
// more stuff
</TouchableOpacity>;
}
}