2017-08-03 79 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 
    } 
} 
}