我尝试将动画应用于屏幕上的2个项目。有两个图像,我想同时在两个图像上应用动画,但是要使用不同的动画。一个应该从左滑动,另一个应该从右滑动。
我搜索了其他来源,但一无所获。有一些示例可以将多个动画一起应用,但这些示例将应用于<Animated.View>
export default class App extends React.Component {
componentWillMount() {
this.animatedMargin = new Animated.Value(0);
// I want to fire both animations from here
setTimeout(() => {
// this._slideAnimation('left');
// this._slideAnimation('right');
// I actually want to know how to achieve this
}, 100);
}
_slideAnimation(direction) {
if (direction === 'left'){
Animated.timing(this.animatedMargin, {
toValue: width,
duration: 1000
}).start();
} else {
Animated.timing(this.animatedMargin, {
toValue: 0,
duration: 1000
}).start();
}
}
render() {
return (
<View style={{ styles.container }}>
{/* I want to slide this from left to right */}
<Animated.View style={[ styles.ainmated, { left: this.animatedMargin } ]}>
<Image source={ left_image } />
</Animated.View>
{/* and this one in reverse direction */}
<Animated.View style={[ styles.ainmated, { right: this.animatedMargin } ]}>
<Image source={ right_image } />
</Animated.View>
</View>
);
}
}
但是以这种方式,一次只能应用一个动画。我曾经尝试过Animated.parallel以便可以并行应用多个动画,但是两个<Animated.View>
标签都将使用相同的动画而不是单独的动画
那么,如何在React native中在同一屏幕上同时在不同对象/组件上实现不同动画?
答案 0 :(得分:2)
您不需要两个动画即可实现这一目标。
这是一个完整的示例:
import * as React from 'react';
import { Text,Animated,View, StyleSheet, Dimensions } from 'react-native';
import Constants from 'expo-constants';
const { width } = Dimensions.get('screen')
const ITEM_SIZE = 60
export default class App extends React.Component {
componentWillMount() {
this.animatedMargin = new Animated.Value(0);
setTimeout(() => {
this._slideAnimation();
}, 1000);
}
_slideAnimation() {
Animated.timing(this.animatedMargin, {
toValue: (width / 2) - ITEM_SIZE,
duration: 1000
}).start()
}
render() {
return (
<View style={ styles.container }>
<Animated.View style={[ styles.animated, { left: this.animatedMargin } ]}>
<View style={[styles.imagePlaceholder, { backgroundColor: '#0070ff'}]} />
</Animated.View>
<Animated.View style={[ styles.animated, { right: this.animatedMargin } ]}>
<View style={[ styles.imagePlaceholder, {backgroundColor: '#008080'} ]} />
</Animated.View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
animated: {
position: 'absolute'
},
imagePlaceholder: {
width: ITEM_SIZE,
height: ITEM_SIZE
}
});