确保在 setState() 调用后,在传递到 Animated.spring() 之前获取最新状态的值。这可以通过使用回调函数或 componentDidUpdate() 来实现。以下是一个示例:
class Example extends React.Component {
state = {
animatedValue: new Animated.Value(0),
currentValue: 0,
};
componentDidUpdate(prevProps, prevState) {
if (this.state.currentValue !== prevState.currentValue) {
Animated.spring(this.state.animatedValue, {
toValue: this.state.currentValue,
useNativeDriver: true,
}).start();
}
}
onPress = () => {
this.setState({ currentValue: this.state.currentValue + 1 });
};
render() {
return (
Click me!
);
}
}
在上面的示例中,我们使用 componentDidUpdate() 来检测 currentValue 的更改,并将其传递到 Animated.spring()来更新动画值。