【发布时间】:2022-01-07 04:12:21
【问题描述】:
所以,我是 React-Native 的字面新手,我刚刚开始尝试一些东西。因此,我遇到了这个问题,即根据数据库中存在的布尔值将按钮的颜色设置为“绿色”或“红色”。
因此,此时,我使用 Google 的“Firebase”作为我的主数据库。
这是我正在尝试解决的基本代码。
import {StatusBar} from 'expo-status-bar';
import React, {Component} from 'react';
import {StyleSheet, Text, View, Pressable, TouchableOpacity} from 'react-native';
import {initializeApp} from 'firebase/app';
import {getDatabase, ref, onValue, set} from 'firebase/database';
import {color} from 'react-native-reanimated';
const firebaseConfig = {};
initializeApp(firebaseConfig);
export default class App extends Component {
constructor() {
super();
this.state = {
l1: this.readVals('l1/'),
};
}
readVals(path) {
const db = getDatabase();
const reference = ref(db, path);
onValue(reference, (snapshot) => {
const value = snapshot.val().obj;
return value;
});
}
setVals(path) {
const db = getDatabase();
const reference = ref(db, path);
const val = this.state.l1;
set(reference, {
obj: !val
});
this.state.l1 = !val;
}
render() {
return (
<View style={styles.container}>
<Pressable
style={({pressed}) => [
{
backgroundColor: this.state.l1 ? '#FF0000' : '#00FF00',
},
styles.button,
]} onPress={() => {this.setVals('l1/')}}>
<Text style={styles.buttonText}>Button</Text>
</Pressable>
<StatusBar style="auto" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FF0000',
alignItems: 'center',
justifyContent: 'center',
},
getButton: {
borderWidth: 1,
borderColor: 'rgba(0,0,0,0.5)',
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'center',
borderWidth: 2,
borderRadius: 7,
marginTop: 20,
width: 100,
height: 50,
backgroundColor: '#00FF00',
},
button: {
flex: 0.15,
borderWidth: 1,
borderColor: 'rgba(0,0,0,0.25)',
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'center',
borderWidth: 2,
borderRadius: 10,
marginTop: 20,
width: 200,
height: 100,
// backgroundColor: '#E84C3D'
},
buttonText: {
fontWeight: 'bold',
fontSize: 20,
},
});
当我按下按钮时,颜色会按预期变化。但是有没有办法根据数据库中存在的值来改变颜色?
例如,在这种情况下,如果“firebase”中位置“l1/”(在我的示例中)的值具有值设置为true,同样,如果“l1/”处的值是false,我希望颜色保持“红色”。
这可以实现吗?
如果是,那么收到的任何帮助对我都非常有帮助。
谢谢。
附:另外,请注意我对 React-Native 领域非常陌生(对不起)。
【问题讨论】:
标签: javascript firebase react-native firebase-realtime-database background-color