javascript - 使用 bool 值淡入动画更改背景颜色 View

标签 javascript animation react-native

<分区>

我正在使用 bool 值来确定 View 的背景颜色

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

...

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

我希望使用 Animated API 的淡入动画可以改变这个颜色开关。

主要问题是,我的 inputRange 是 bool 值。

感谢您的宝贵时间。

最佳答案

这是你想要的吗?

enter image description here

您可以为 style 对象的 opacity 属性设置动画。您有一个背景颜色为 #e9e9e9 的主 View 和一个背景颜色为 #8bc34a 的嵌套 Animated.View > 但是一开始opacity是0,toggle时opacity变成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;

关于javascript - 使用 bool 值淡入动画更改背景颜色 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49117298/

相关文章:

html - slider 动画错误

iphone - 防止编辑模式下 UITableView 中的某个部分缩小动画?

javascript - Bootstrap 安装在 ReactJS 应用程序中但没有样式

javascript - 在 JavaScript 中用冒号声明一个变量

javascript - javascript 正则表达式匹配任何脚本中所有非单词字符的正确正则表达式范围是多少?

javascript - 如何使用下拉框更改样式表?

swift - UIView 动画表现怪异

ios - 在react-native-maps上需要未知模块 "undefined"

react-native - 如何修复 'undefined is not an object (evaluating ' NativeModules ["SQLite"][方法 ]')'

android - 如何在 native react 中对 TextInput 应用点击事件