使用条件反应本机样式

时间:2017-08-03 08:19:31

标签: react-native

我是新来的本地人。我正在尝试在出现错误时更改TextInput的样式。

如何让我的代码不那么丑?

<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>

3 个答案:

答案 0 :(得分:57)

使用StyleSheet.create进行这样的样式合成,

文字有效文字无效文字制作样式。

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

然后将它们与一系列样式组合在一起。

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

对于数组样式,后者将合并为前者,并使用相同键的覆盖规则。

答案 1 :(得分:3)

按以下方式更新您的代码:

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

然后在你的类组件之外写下:

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
   }
 }
}

答案 2 :(得分:0)

有两种方法: 通过内联或调用函数。

1)

const styles = StyleSheet.create({
    green: {
        borderColor: 'green',
    },
    red: {
        borderColor: 'red',
    },
    
});

<TextInput style = {[styles.otpBox, this.state.stateName ? styles.green : styles.red ]}

2)<TextInput style = {[styles.otpBox, this.getstyle(this.state.showValidatePOtp) ]}

getstyle(val){

if(val){
  return{borderColor:'red'};
}
else{
  return{borderColor:'green'};

}}