Вот закуска https://snack.expo.io/@ziyoshams/frisky-watermelon, и попробуйте изучить код.Ваша ошибка исходила от onLayout
, но сильно изменилась.Вот код:
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
Animated,
Dimensions,
TouchableWithoutFeedback,
} from 'react-native';
const { width, height } = Dimensions.get('window');
export default class App extends Component {
state = {
animation: new Animated.ValueXY(),
scaleAnimation: new Animated.Value(1),
box1RotateAnimation: new Animated.Value(0),
box2RotateAnimation: new Animated.Value(0),
};
startAnimation = () => {
Animated.parallel([
Animated.timing(this.state.animation.y, {
toValue: height / 2 - this._height / 2,
duration: 500,
useNativeDriver: true,
}),
Animated.timing(this.state.animation.x, {
toValue: width / 2 - this._width / 2,
duration: 500,
useNativeDriver: true,
}),
Animated.timing(this.state.scaleAnimation, {
toValue: 2,
duration: 500,
useNativeDriver: true,
}),
]).start(() => {
Animated.sequence([
Animated.timing(this.state.box1RotateAnimation, {
toValue: 180,
duration: 500,
useNativeDriver: true,
}),
Animated.timing(this.state.box2RotateAnimation, {
toValue: 180,
duration: 500,
useNativeDriver: true,
}),
]).start();
});
};
saveDimensions = e => {
this._width = e.nativeEvent.layout.width;
this._height = e.nativeEvent.layout.height;
};
render() {
const frontInterpolate = this.state.box1RotateAnimation.interpolate({
inputRange: [0, 180],
outputRange: ['0deg', '90deg'],
});
const backInterpolate = this.state.box2RotateAnimation.interpolate({
inputRange: [0, 180],
outputRange: ['90deg', '0deg'],
});
const parentAnimation = {
transform: [
{
translateX: this.state.animation.x,
translateY: this.state.animation.y,
scale: this.state.scaleAnimation,
},
],
};
const box1Animation = {
transform: [
{
rotateY: frontInterpolate,
},
],
};
const box2Animation = {
transform: [
{
rotateY: backInterpolate,
},
],
};
return (
<View style={styles.container}>
<TouchableWithoutFeedback
onPress={this.startAnimation}
onLayout={this.saveDimensions}>
<Animated.View style={[styles.box, parentAnimation]}>
<Animated.View style={[styles.box1, box1Animation]}>
<Text>Front</Text>
</Animated.View>
<Animated.View style={[styles.box2, box2Animation]}>
<Text>Back</Text>
</Animated.View>
</Animated.View>
</TouchableWithoutFeedback>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
box: {
width: 150,
height: 150,
position: 'absolute',
top: 0,
left: 0,
},
box1: {
width: 150,
height: 150,
backgroundColor: 'tomato',
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
top: 0,
left: 0,
},
box2: {
width: 150,
height: 150,
backgroundColor: 'green',
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
top: 0,
left: 0,
},
});