2017-08-03 88 views
2

我是新的反應原生。我試圖在發生錯誤時更改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> 

回答

4

使用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.invalid : styles.valid]} 
</TextInput> 

對於數組樣式,後者將合併成前一個,併爲相同的鍵覆蓋規則。

+0

這看起來不錯,謝謝! –

0

更新您的代碼如下:

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