使用条件反应本机样式

Kel*_*vin 28 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>
Run Code Online (Sandbox Code Playgroud)

Val*_*Val 89

StyleSheet.create做喜欢这种风格组成,

文本,有效文本无效文本创建样式.

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

然后将它们与样式数组合在一起.

<TextInput
    style={[styles.text, touched && invalid ? styles.textinvalid : styles.textvalid]}
</TextInput>
Run Code Online (Sandbox Code Playgroud)

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

  • styles.textinvalid和styles.textvalid而不是styles.invalid:styles.valid (2认同)

Pra*_*rle 8

有两种方法,内联或调用函数:

1)

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

<TextInput style={[styles.otpBox, this.state.stateName ?
    styles.green :
    styles.red ]} />
Run Code Online (Sandbox Code Playgroud)
getstyle(val) {
    if (val) {
        return { borderColor: 'red' };
    }
    else {
        return { borderColor: 'green' };
    }
}

<TextInput style={[styles.otpBox, this.getstyle(this.state.showValidatePOtp)]} />
Run Code Online (Sandbox Code Playgroud)


Roh*_*ale 6

如下更新代码:

<TextInput style={getTextStyle(this.state.touched, this.state.invalid)}></TextInput>
Run Code Online (Sandbox Code Playgroud)

然后在类组件之外,编写:

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
   }
 }
}
Run Code Online (Sandbox Code Playgroud)