【问题标题】:A better way to change the background color using a ternary operator使用三元运算符更改背景颜色的更好方法
【发布时间】:2018-10-23 02:39:05
【问题描述】:

目前,我正在使用一个函数来切换 hasBeenClicked,然后我使用条件来确保仅当 hasBeenClicked 为 true 时才更改背景颜色。我更喜欢在 style 道具中使用三元运算符来处理逻辑。

    let randomHex = () => {


  let letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
    // console.log('here is your random hex color', color);
  }
  return color;

}

export default class App extends Component {
  constructor() {
    super()
    this.state = {
      hasBeenClicked: false

    }
  }


  changeColor = () => {
    this.setState({
      hasBeenClicked: !this.state.hasBeenClicked
    })
    if (this.state.hasBeenClicked === true) {
      this.setState({
        backgroundColor: randomHex()
      })
    }


  }
  render() {
    return (
      <View style={[styles.container, { backgroundColor: this.state.backgroundColor }]}>
        <TouchableOpacity
          onPress={this.changeColor}
        >
          <Text style={styles.welcome}>
            Welcome to React Native!
        </Text>
        </TouchableOpacity>


      </View>
    );
  }
}

我试过了

<View style={[styles.container, { backgroundColor: {this.state.hasBeenClicked: this.state.backgroundColor ? 'green'} }]}>

有什么更好的/正确的方法来做到这一点?

【问题讨论】:

    标签: react-native styling ternary-operator


    【解决方案1】:

    你的三进制不正确:

    { this.state.hasBeenClicked : this.state.backgroundColor ? 'green'}

    应该是

    { this.state.hasBeenClicked ? this.state.backgroundColor : 'green'}

    【讨论】:

    • 就是这样。我不敢相信我搞砸了这么简单的事情。
    • 我们都做到了 :) 通常当我们盯着代码看太久哈哈
    【解决方案2】:

    一种方法是创建 2 个具有不同背景颜色的不同 CSS 类。例如,

    .red: {
      background: 'red'
    }
    .blue: {
      background: 'blue'
    }
    

    现在在您的&lt;View /&gt; 中,您可以根据您的this.state.hasbeenClicked 值动态分配类。例如,

    render(){
      const className = this.state.hasBeenClicked ? 'blue' : 'red'
      return(
        <View className={className}>
          // rest of your code
        </View>
      )
    }
    

    【讨论】:

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