【问题标题】:Change Background Color View with Fade In animation from boolean [duplicate]从布尔值更改背景颜色视图与淡入动画[重复]
【发布时间】:2018-08-13 12:17:08
【问题描述】:

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

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

...

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

我希望这个颜色开关随着使用 Animated API 的淡入动画而改变

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

感谢您的宝贵时间。

【问题讨论】:

  • 有没有可能让你的inputRange把两种颜色转换成整数?

标签: javascript animation react-native


【解决方案1】:

这是你想要的吗?

您可以为style 对象的opacity 属性设置动画。您有一个主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;

【讨论】:

  • 用作动画值是一个很好的技巧。因此,例如,您如何从红色变为绿色?如果你坚持 opacity 属性,似乎你不能
猜你喜欢
  • 1970-01-01
  • 2021-07-06
  • 2014-07-06
  • 1970-01-01
  • 2012-05-31
  • 2015-10-15
  • 2014-09-16
  • 2016-12-13
  • 1970-01-01
相关资源
最近更新 更多