React Native styling with conditional

2020-05-19 20:09发布

I'm new to react native. I'm trying to change the styling of the TextInput when there is an error.

How can I make my code not as ugly?

<TextInput
      style={touched && invalid?
        {height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10, borderWidth: 2, borderColor: 'red'} :
        {height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10}}
</TextInput>

2条回答
叛逆
2楼-- · 2020-05-19 20:33

Update your code as following:

<TextInput style={getTextStyle(this.state.touched, this.state.invalid)}></TextInput>

Then outside your class component, write:

getTextStyle(touched, invalid) {
 if(touched && invalid) {
  return {
    height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10, borderWidth: 2, borderColor: 'red'
  }
 } else {
   return {
      height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10
   }
 }
}
查看更多
甜甜的少女心
3楼-- · 2020-05-19 20:46

Use StyleSheet.create to do style composition like this,

make styles for text, valid text, and invalid text.

const styles = StyleSheet.create({
    text: {
        height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10, 
    },
    textvalid: {
        borderWidth: 2,
    },
    textinvalid: {
        borderColor: 'red',
    },
});

and then group them together with an array of styles.

<TextInput
    style={[styles.text, touched && invalid ? styles.textinvalid : styles.textvalid]}
</TextInput>

For array styles, the latter ones will merge into the former one, with overwrite rule for the same keys.

查看更多
登录 后发表回答