我的问题很具体:
我如何链接两个动画,以便我可以将一个项目从 X 移动到 Y,然后从 Y 移动到 Z?
我得到一个 View ,我想从位置 (x,y) 到 (x+a, y+b) 设置动画,然后让它“悬停”在那里。我原以为动画会从它停止的地方继续播放,但事实证明我错了……当它执行循环时,它会从初始值 (0,0) 而不是最后一个位置重新开始。
// this is in my index.js
class App extends Component {
constructor(props) {
super(props);
this.translateValue = new Animated.ValueXY({x: 0, y: 0});
}
componentDidMount() {
Animated.sequence([
Animated.timing(this.translateValue,
{ toValue: { x: 30, y: 30 }, duration: 1000, easing: Easing.linear }),
Animated.loop(
Animated.sequence([
Animated.timing(this.translateValue,
{ toValue: { x: 30, y: 20 }, duration: 1000, easing: Easing.linear }),
Animated.timing(this.translateValue,
{ toValue: { x: 30, y: 30 }, duration: 1000, easing: Easing.linear })
]),
{ iterations: 1000 })
]).start();
}
render() {
const translateTransform = this.translateValue.getTranslateTransform();
return (
<View style={{ flex: 1 }}>
<Animated.View style={{
height: 30,
width: 30,
backgroundColor: "blue",
position: "absolute",
transform: translateTransform }} />
</View>
);
}
}
序列的第一个动画结束后,我是否需要调用 this.translateValue.setValue({x: 30, y: 30 })
?如果是,怎么办?
编辑:我正在寻找一种声明机制。不幸的是,我认为没有声明性的方式来调用 setValue
作为动画合成的一部分。
最佳答案
Animated
有一个结束回调,您可以像这样链接两个动画:
constructor() {
this.state = {
translation: 1,
}
this.fade = new Animated.Value(0)
}
fade_1(){
this.fade.setValue(0)
this.setState({translation: this.fade.interpolate({
inputRange: [0, 1],
outputRange: [ 1 , 0]
})})
Animated.timing(
this.fade,
{
toValue: 1,
duration: 3000,
useNativeDriver: true
}
).start(() => this.fade_2()) // we chain animation's here
}
fade_2(){
this.fade.setValue(0)
this.setState({translation: this.fade.interpolate({
inputRange: [0, 1],
outputRange: [ 0 , 1]
})})
Animated.timing(
this.fade,
{
toValue: 1,
duration: 3000,
useNativeDriver: true
}
).start()
}
render() {
return(
<View style={{backgroundColor:'#fff' , flex:1 ,alignItems: 'center' , justifyContent: 'center' }}>
<Animated.View style={{width: 150 , height: 150 , alignItems: 'center', opacity: this.state.translation }}>
<Image source={require('YOUR IMAGE URI')} style={{width: 150 , height: 150}}/>
</Animated.View>
<TouchableOpacity style={{flex: 1 , alignItems: 'center', justifyContent: 'center'}}
onPress={()=> this.fade_1()}
>
<Text> START </Text>
</TouchableOpacity>
</View>
)
}
关于javascript - 如何在 native react (声明式)中将多个动画链接在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48135919/