Quiero que el color de fondo de un ajuste preestablecido de Pressable sea azul o verde según el valor presente en firebase, es decir, si es cierto en firebase, el color de Pressable es verde, de lo contrario, es azul.
Además, si presiono el botón, cambia los valores en la base de fuego y también cambia el color del botón.
En mi código, cuando hago clic en Pressable , el color cambia y el valor también se intercambia en firebase, pero no tiene el color predeterminado cuando cargo la aplicación.
El botón debe tener el color verde en el momento en que se carga si el valor en firebase es verdadero.
Aquí está mi código.
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 = { value: this.readVals('value/'), }; } 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.value ? '#FF0000' : '#00FF00', }, styles.button, ]} onPress={() => {this.setVals('value/')}}> <Text style={styles.buttonText}>Button</Text> </Pressable> <StatusBar style="auto" /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#FF0000', alignItems: 'center', justifyContent: 'center', }, 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, }, buttonText: { fontWeight: 'bold', fontSize: 20, }, }); ¿Es posible tener el color de fondo predeterminado?
Por favor, hágame saber cómo.
Gracias.
Debe cambiar el estado solo después de obtener el valor de esta manera:
this.state = { value: null; }; readVals(path) { const db = getDatabase(); const reference = ref(db, path); onValue(reference, (snapshot) => { const value = snapshot.val().obj; this.setState({value: value}); }); }