You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何根据Firebase数据库布尔值动态修改按钮颜色

解决方案

问题核心原因

  • Firebase读取数据是异步操作,你在构造函数中直接调用readVals赋值无法拿到返回结果,onValue回调的返回值不会被赋值给state
  • 没有主动调用setState更新状态,React不会触发页面重新渲染,所以初始加载时按钮颜色不会跟着数据库值更新
  • 直接修改this.state的值不符合React状态更新规范,可能导致页面不刷新的问题
  • 类组件自定义方法未绑定this,运行时可能出现找不到对应属性的报错

修改后的完整代码

import {StatusBar} from 'expo-status-bar';
import React, {Component} from 'react';
import {StyleSheet, Text, View, Pressable} from 'react-native';

import {initializeApp} from 'firebase/app';
import {getDatabase, ref, onValue, set} from 'firebase/database';

// 替换为你自己的firebase配置
const firebaseConfig = {};
initializeApp(firebaseConfig);

export default class App extends Component {
  constructor() {
    super();
    // 先给l1设置初始默认值
    this.state = {
      l1: false,
    };
    // 绑定方法的this指向,避免运行时报错
    this.readVals = this.readVals.bind(this);
    this.setVals = this.setVals.bind(this);
  }

  // 组件挂载完成后自动调用,拉取Firebase初始值
  componentDidMount() {
    this.readVals('l1/');
  }

  readVals(path) {
    const db = getDatabase();
    const reference = ref(db, path);
    onValue(reference, (snapshot) => {
      const value = snapshot.val().obj;
      // 拿到数据库值后更新state,触发页面重新渲染
      this.setState({
        l1: value
      });
    });
  }

  setVals(path) {
    const db = getDatabase();
    const reference = ref(db, path);
    const newVal = !this.state.l1;
    set(reference, {
      obj: newVal
    });
    // 用React指定的setState方法更新状态,不要直接修改this.state
    this.setState({
      l1: newVal
    });
  }
  render() {
    return (
      <View style={styles.container}>
        <Pressable
          style={({pressed}) => [
            {
              // 修正颜色判断逻辑:l1为true显示绿色,false显示红色
              backgroundColor: this.state.l1 ? '#00FF00' : '#FF0000',
            },
            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,
  },
  buttonText: {
    fontWeight: 'bold',
    fontSize: 20,
  },
});

调整说明

  1. 移除了未使用的导入语句,避免无效代码报错
  2. 新增componentDidMount生命周期函数,组件加载完成后自动拉取数据库初始值
  3. 修改readVals逻辑,拿到数据库返回值后主动调用setState更新状态,自动触发按钮颜色刷新
  4. 修正了按钮颜色的判断逻辑,完全符合你要求的「值为true显示绿色,为false显示红色」
  5. 调整setVals的状态更新方式,符合React开发规范,避免后续出现页面不刷新的问题

内容的提问来源于stack exchange,提问作者Just_ish1122

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:15:04