试图将方形块从屏幕的一角移到屏幕的中心,但该运动呈锯齿状且不平滑。我尝试了useNativeDriver:是的,但是没有用;我有一个错误。我是否缺少某些东西,或者需要采取其他措施来使运动平稳?似乎只有在我同时翻译x和y时才会发生这种情况,例如在这个问题中。
这是下面的代码:
import React, {Component} from 'react';
import
{
StyleSheet,
View,
Text,
Animated,
Dimensions,
TouchableWithoutFeedback
}
from 'react-native';
export default class App extends Component {
state = {
animation: new Animated.ValueXY()
};
startAnimation = () => {
const {width, height} = Dimensions.get("window");
Animated.parallel([
Animated.timing(this.state.animation.y, {
toValue: (height / 2) - (this._height / 2),
duration: 500
}),
Animated.timing(this.state.animation.x, {
toValue: (width / 2) - (this._width / 2),
duration: 500
})
]).start();
}
saveDimensions = (e) => {
this._width = e.nativeEvent.layout.width;
this._height = e.nativeEvent.layout.height;
}
render() {
const animatedStyles = {
transform: [
{
translateX: this.state.animation.x
},
{
translateY: this.state.animation.y
}
]
}
return (
<View style={styles.container}>
<TouchableWithoutFeedback
onPress={this.startAnimation}
onLayout={this.saveDimensions}
>
<Animated.View
style={[styles.box, animatedStyles]}
/>
</TouchableWithoutFeedback>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
box: {
width: 150,
height: 150,
backgroundColor: 'tomato',
position: 'absolute',
top: 0,
left: 0,
},
});