我是新来的响应本机动画功能的人。我希望使用它来淡入和淡出按钮时的元素。下面的代码可在页面加载时在元素中淡入淡出,但是将其淡出的按钮不会如我所愿地使其淡出。有人可以解释我在做什么错。谢谢。
class FadeComponent extends Component {
constructor(props) {
super(props)
this.state = {
fadeAnim: new Animated.Value(0), // Initial value for opacity: 0
}
this.fadeOut = this.fadeOut.bind(this);
}
componentDidMount() {
Animated.timing( // Animate over time
this.state.fadeAnim, // The animated value to drive
{
toValue: 1, // Animate to opacity: 1 (opaque)
duration: 2000, // 2000ms
}
).start(); // Starts the animation
}
fadeOut(){
this.setState({fadeAnim: new Animated.Value(1)})
Animated.timing( // Animate over time
this.state.fadeAnim, // The animated value to drive
{
toValue: 0, // Animate to opacity: 1 (opaque)
duration: 2000, // 2000ms
}
).start(); // Starts the animation
}
render() {
let { fadeAnim } = this.state;
return (
<View style = {{ backgroundColor: '#1a8cff', marginTop: 100 }}>
<Animated.View style={{ ...this.props.style, opacity: fadeAnim }} >
{this.props.children}
<View style = {{ backgroundColor: '#000000', height: 50, width: 50 }}>
</View>
</Animated.View>
<TouchableOpacity onPress={this.fadeOut} >
<Text style={{ color: 'white', textDecorationLine: 'underline', marginTop: 10 }}>
fade out
</Text>
</TouchableOpacity>
</View>
);
}
}
答案 0 :(得分:5)
因为函数setState是异步的。这应该可以解决您的问题:
this.setState({ fadeAnim: new Animated.Value(1) },
() => {
Animated.timing( // Animate over time
this.state.fadeAnim, // The animated value to drive
{
toValue: 0, // Animate to opacity: 1 (opaque)
duration: 2000, // 2000ms
}
).start();
})