【问题标题】:How to compare color object in react native while setting state如何在设置状态时比较本机反应中的颜色对象
【发布时间】:2019-04-20 07:10:51
【问题描述】:

有人可以帮我比较反应原生的颜色对象吗? 一般来说,我会很快这样做:

if aColorObj == UIColorClass.white{
  aColorObj = UIColorClass.gray
}

如何在下面的 react native 中做类似的事情:

onPressLearnMore() {

  this.setState = {
    /*
      how to write this:
       if mbackgroundColor == 'white'{
      mbackgroundColor = 'red'
      }else if mbackgroundColor == 'gray'{
      mbackgroundColor = 'white'
      } 
    */
  };
}

谢谢:)

【问题讨论】:

    标签: react-native conditional state


    【解决方案1】:

    这里最简单的解决方案也是,将初始背景颜色保存在一个状态中,拥有可用于比较颜色的颜色对象。

    const Colors = {
      Grey: '#DCDCDC',
      White: '#FFFFFF',
      Blue: '#0000FF',
      Black: '#000000',
    };
    
    
    state = {
      backgroundColor: Colors.White,
    };
    
    <View
        style={[
          styles.container,
          { backgroundColor: this.state.backgroundColor }, // set background color here from state
        ]}>
    

    然后你可以使用一个函数来检查背景颜色。

    checkBackgroundColor = () => {
    
      if (this.state.backgroundColor === Colors.Blue) {
        console.log("It's blue");
    
        this.setState({
          backgroundColor: Colors.White,
        });
      }
      ....
    };
    

    snack example

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 2020-09-10
      相关资源
      最近更新 更多