我试图通过处理按钮点击来切换视图的不透明度和动画值,但我没有得到所需的结果,除了第一次点击按钮外,它会逐渐消失(不透明度=0(,但当我再次按下按钮时,什么也没发生,我看不到我的视图。这是代码:
export default class App extends React.Component {
state = {
animation: new Animated.Value(1)
}
startAnimation = () => {
const { animation } = this.state
Animated.timing(animation, {
toValue: animation === 0 ? 1 : 0,
duration: 1000
}).start()
}
render() {
const animatedStyle = {
opacity: this.state.animation
}
return (
<View style={styles.container}>
<Animated.View style={[styles.box, animatedStyle]} />
<Button title="Toggle fade" onPress={this.startAnimation} />
</View>
);
}
} .
有人知道我做错了什么吗?
谢谢!
我认为这是因为您不更改动画值的状态,并且这个const { animation } = this.state
将始终具有相同的值,而toValue: animation === 0 ? 1 : 0,
也将具有相同的数值。我试图向你展示我是如何在我的项目中做到这一点的,但你必须根据自己的需要进行更新。
export default class App extends React.Component {
state = {
animation: new Animated.Value(1),
isVisible: false //add a new value to check your state
}
startAnimation = () => {
const { isVisible } = this.state
Animated.timing(animation, {
toValue: isVisible === 0 ? 1 : 0,
duration: 1000
}).start(() => {
this.setState({ isVisible: !this.state.isVisible });//set the new state, so the next click will have different value
})
}
render() {
const animatedStyle = {
opacity: this.state.animation
}
return (
<View style={styles.container}>
<Animated.View style={[styles.box, animatedStyle]} />
<Button title="Toggle fade" onPress={this.startAnimation} />
</View>
);
}
} .
我使用的是:
let val = this.state.sliderOpen ? 0.8 : 0;
Animated.timing( // Animate over time
this.state.sliderAnimation, // The animated value to drive
{
toValue: val, // Animate to opacity: 1 (opaque)
duration: 5, // Make it take a while
}
).start();
this.setState({
sliderOpen : !this.state.sliderOpen
})
也许可以尝试提取要更改的值。
多亏了@oma,我才得以成功,下面是小吃:在React Native 中切换不透明度
除此之外,我还发现了一篇关于这个功能可以重用的好文章:
React Native 中的出现和消失动画
这是工作示例的小吃,稍作修改。
动画不透明度
这个解决方案看起来不错,希望你能从中受益。
我制作了一个节点包react原生淡入淡出,它用动画值切换视图的不透明度。您可以查看源代码来了解它是如何实现的,但这里有一个简化的版本:
import React, {PureComponent} from 'react';
import {Animated} from 'react-native';
export default class FadeInOut extends PureComponent {
state = {
fadeAnim: new Animated.Value(this.props.visible ? 1 : 0),
};
componentDidUpdate(prevProps) {
if (prevProps.visible !== this.props.visible) {
Animated.timing(this.state.fadeAnim, {
toValue: prevProps.visible ? 0 : 1,
duration: 300,
}).start();
}
}
render() {
return (
<Animated.View style={{...this.props.style, opacity: this.state.fadeAnim}}>
{this.props.children}
</Animated.View>
);
}
}