使用条件反应原生样式 [英] React Native styling with conditional

查看:33
本文介绍了使用条件反应原生样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是本机反应的新手.我正在尝试在出现错误时更改 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.

这篇关于使用条件反应原生样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆