使用三元运算符更改背景颜色的更好方法

A better way to change the background color using a ternary operator

目前,我正在使用一个函数来切换 hasBeenClicked,然后我使用一个条件来确保仅当 hasBeenClicked 为真时才更改背景颜色。我更愿意在 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'} }]}>

什么是更好的 way/correct 方法?

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

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

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

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

你的三进制不正确:

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

应该是

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