【问题标题】:Change Background color with Switch case使用 Switch case 更改背景颜色
【发布时间】:2018-09-22 12:32:38
【问题描述】:
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import AwesomeButton from 'react-native-really-awesome-button';

let randomHex = () => {
  let letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  console.log(color);
  return color;
};

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };

    this.states = {
      backgroundColor: randomHex(),
    };
  }

  onPress = () => {
    this.setState({
      count: this.state.count + 1,
    });
  };

  renkDegis = (count, color) => {
    switch (count) {
      case 10:
        color = 'black';
        break;

      case 20:
        b = this.randomHex();
        break;

      default:
        null;
    }
  };

  render() {
    return (
      <View
        style={{
          flex: 1,
          alignItems: 'center',
          backgroundColor: this.renkDegis(this.state.count),
        }}>
        <Text style={styles.textDesign}>{this.state.count}</Text>
        <TouchableOpacity
          style={styles.btnStyle}
          onPress={this.onPress}></TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: randomHex(),
    alignItems: 'center',
    //  justifyContent: 'center',
  },
});

我想在计数为 10、20 和 30 时更改颜色。但我错在哪里? 你能编译我的代码吗?当我按十次按钮时,它会给我一个警告。

我创建了 randomHex() 并使用它。但它给了我一个警告。

【问题讨论】:

  • this.states...?

标签: javascript react-native


【解决方案1】:

你应该从renkDegis函数返回值,

样本

renkDegis = (count) => {
  let choosen;

  switch (count) {
    case 10:
      choosen = 'black';
      break;
    case 20:
      choosen = randomHex();
      break;
    default:
      null;
  }

  return choosen;
};

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    • 2012-07-10
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多