首页 > 解决方案 > 使用三元运算符更改背景颜色的更好方法

问题描述

目前,我正在使用一个函数来切换 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-nativestylingternary-operator

解决方案


你的三元不正确:

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

应该

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


推荐阅读