写作时间:2020/7/20
开发平台:macOS
目标平台:Android、iOS
现要实现一个组件的背景颜色交替闪烁(两个颜色来回变换),考虑Animated组件是个可行的选择,下面给出具体操作方法
1、首先需要在this.state当中维护变量color,背景颜色依据它的变化来进行改变
this.state = {
color: new Animated.Value(0),
};
2、添加如下方法,该方法实现的内容是先在一秒之内将color的值由0变为1,再用一秒的时间将color的值由1变回0,如此循环往复。这个方法可以灵活的添加在任何位置,如果放在componentDidMount方法当中,则该组件一开始就会执行该方法,当然也可以绑定到按钮或其他响应组件进行控制。
startAnimated = () => {
const animationSlider = Animated.sequence([
Animated.timing(this.state.color, {
toValue: 1,
duration: 1000,
}),
Animated.timing(this.state.color, {
toValue: 0,
duration: 1000,
}),
]);
Animated.loop(animationSlider).start();
};
3、目前存在的问题是,color的变化无法反应在颜色的变化上,因此需要在render方法当中添加如下代码。interpolate方法实现了数值和颜色的对应,其中0对应orange,1对应cyan,当this.state.color不断变化时,其输出的bgColor会依据color的数值输出对应的颜色
var bgColor = this.state.color.interpolate({
inputRange: [0, 1],
outputRange: ['orange', 'cyan'],
});
4、最后在return方法中添加如下组件即可
return(
<Animated.View style={{backgroundColor: bgColor}}>
<View style={{width: 100, height: 100}} />
</Animated.View>
);