使用淡入淡出动画从布尔[重复]更改背景颜色视图

问题描述 投票:1回答:1

这个问题在这里已有答案:

我正在使用布尔值来确定视图的背景颜色

const selectColor = isSelected ? "#8bc34a" : "#e9e9e9";

...

<TouchableOpacity onPress={toggleSelection}>
 <View style={{ backgroundColor: selectColor }}>
 </View>
</TouchableOpacity>

我想这个颜色开关使用Animated API用FadeIn Animation改变

主要问题是,我的inputRange是一个布尔值。

谢谢你的时间。

javascript animation react-native
1个回答
1
投票

这是你想要的吗?

enter image description here

您可以为opacity对象的style属性设置动画。你有一个主要的View,其背景颜色是#e9e9e9和嵌套的Animated.View,其背景颜色是#8bc34a但不透明度最初是0,当切换时,不透明度变为1,上面的Gif的代码是:

class TestScreen extends Component {
    constructor(props) {
        super(props);

        this.opacity = new Animated.Value(0);

        this.toggleBackgroundColor = this.toggleBackgroundColor.bind(this);
    }

    toggleBackgroundColor() {
        Animated.timing(this.opacity, {
            toValue: this.opacity._value ? 0 : 1,
            duration: 1000
        }).start();
    }

    render() {
        return (
            <View
                style={{
                    flex: 1, justifyContent: 'center',
                    alignItems: 'center',
                    backgroundColor: '#8BC34A'
                }}
            >
                <TouchableOpacity
                    style={{ borderWidth: 1, borderColor: '#4099FF', zIndex: 1 }}
                    onPress={this.toggleBackgroundColor}
                >
                    <Text style={{ fontSize: 18, color: '#4099FF', margin: 16 }}>
                        Toggle
                    </Text>
                </TouchableOpacity>
                <Animated.View
                    style={{
                        position: 'absolute',
                        left: 0, right: 0, bottom: 0, top: 0,
                        justifyContent: 'center',
                        alignItems: 'center',
                        backgroundColor: '#E9E9E9',
                        opacity: this.opacity
                    }}
                />
            </View>
        );
    }
}

export default TestScreen;
© www.soinside.com 2019 - 2024. All rights reserved.