【问题标题】:In React Native, is there a way to change the color of the button based on a boolean from a database?在 React Native 中,有没有办法根据数据库中的布尔值更改按钮的颜色?
【发布时间】: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


    【解决方案1】:

    对于reRender 屏幕,您必须使用state 并且当它再次更改您的屏幕render 时。看来你用过那个。但你可以尝试另一种方式。在第一次打电话时,您可以像这样在componentDidMount 中获取您的数据:

      componentDidMount() {
        console.log("componentDidMount");
         this.setState({  l1: this.readVals('l1/') });
      }
    
    

    如果 l1 改变了,它应该适合你。

    另一方面,如果您想在更改数据库后立即更改UI,您可以尝试两种方式。起初你使用 socket programming 就像 signalR 组件。欲了解更多信息this link

    firebase 中的第二种方式,您可以使用firebaseMessaging,这样当数据库更改时,json 数据将通过notification 发送。更多信息see this

    【讨论】:

    • 感谢您的回复。但不幸的是,这并没有什么好处。我希望根据数据库中的布尔值将背景颜色默认设置为绿色或红色。
    • 另外,当我更改数据库中的值时,它不会更改背景颜色。
    • 在我的解决方案中,当数据库更改时,用户打开屏幕颜色时会发生变化。但是如果你想在数据库发生变化时立即改变它,你必须尝试另一种方式。我编辑我的答案并解释一下。
    • @MeisaamSaba 很抱歉,但当我尝试实现您的代码时,它并没有改变加载页面时按钮背景的颜色。也许您可能遗漏了某些与您的代码不同的部分?
    • 首先在加载屏幕上使用控制台日志检查您的“complonentDidmont”是否被调用。然后像这样检查设置后的状态值: this.setState({ l1: this.readVals('l1/') }, () => console.log(this.state.l1), )
    【解决方案2】:

    当您处理类基础组件时,您可以在 componentWillMount 中调用 firebase 函数并获取颜色并将其保存到您的状态。

    componentWillMount 在渲染之前运行,因此一旦您获得数据,您就可以设置状态,然后通过该状态您可以更改按钮的颜色。

    试试这个

    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/'),
        };
      }
    
      componentWillMount() {
        const value = this.readVals('l1/');
        this.setState({l1: value});
      }
    
      readVals(path) {
        const db = getDatabase();
        const reference = ref(db, path);
        onValue(reference, (snapshot) => {
          const value = snapshot.val().obj;
          return value;
        });
      }
      render() {
        return (
          <View style={styles.container}>
            <Pressable
              style={({pressed}) => [
                {
                  backgroundColor: this.state.l1 ? '#FF0000' : '#00FF00',
                },
                styles.button,
              ]}>
              <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 是实时的,所以我认为是的,它会显示更改。
    • 对不起,我认为这里没有变化。
    • 您第一次获得了您在数据库中设置的正确颜色吗?
    • 我想你应该看看&lt;Pressable style={({ pressed }) =&gt; [{ backgroundColor: this.state.l1 ? '#FF0000' : '#00FF00' }, styles.button ]} 这行,我按一下颜色应该会改变。
    猜你喜欢
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 2014-12-30
    • 2023-01-28
    • 1970-01-01
    • 2019-07-06
    • 2019-07-07
    • 2022-06-15
    相关资源
    最近更新 更多