gpt4 book ai didi

javascript - 使用 React Native Animated 淡入淡出元素

转载 作者:行者123 更新时间:2023-12-03 12:48:08 27 4
gpt4 key购买 nike

我是 react 原生动画功能的新手。我希望用它来淡入和淡出按钮按下的元素。下面的代码可以在页面加载时淡入元素,但是淡出它的按钮不会像我期望的那样淡出它。有人可以解释我做错了什么。谢谢你。

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>
);
}
}

最佳答案

因为函数 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();
})

关于javascript - 使用 React Native Animated 淡入淡出元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51549964/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com