使用条件反应原生样式

新手上路,请多包涵

我是新来的反应本地人。出现错误时,我正在尝试更改 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>

原文由 Kelvin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 376
1 个回答

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

对于数组样式,后者将合并到前者中,并具有相同键的覆盖规则。

原文由 Val 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏