使用条件反应原生样式
问题描述:
我是本机反应的新手.我正在尝试在出现错误时更改 TextInput 的样式.
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>
答
使用 StyleSheet.create
来做这样的样式组合,
Use StyleSheet.create
to do style composition like this,
为文本、有效文本和无效文本制作样式.
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>
对于数组样式,后面的会合并到前面的,对相同的key有覆盖规则.
For array styles, the latter ones will merge into the former one, with overwrite rule for the same keys.