我是个新来的土生土长的人.我试图在出现错误时更改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>

推荐答案

StyleSheet.create来做这样的风格组合,

制作textvalid textinvalid text的样式.

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>

对于数组样式,后一种样式将合并到前一种样式中,对相同的键使用覆盖规则.

React-native相关问答推荐

使用NextJS映射从数组中提取用户角色

如何重复使用expo 音频对象S录音?

React Navigation—从标题按钮打开模式

替换数组中的一个元素就是替换数组中的所有元素?

React Native:任务 ':app:checkDebugDuplicateClasses' 执行失败

react-native 根据状态隐藏显示按钮

我如何限制 FlatList 中的元素并增加负载?

加载作为props传递的图像

如何在带有decorator 的 react-native 0.56 (Babel 7) 中使用 mobx

请求无法完成,因为您已超出配额

React Native 开发中的/ios/index/DataStore文件夹是什么

命令失败:gradlew.bat installDebug error whenever installing dependencies like navigation, firebase, icons etc in React-Native

如何在 array.map 中的每个元素之后添加逗号,除了 React JSX 中的最后一个元素

No such property: ABI for class: org.gradle.api.tasks.OutputFile

将图标添加到drawer抽屉react-navigation v5

在 React-Native 中手动设置 opacity 的 onPress of TouchableOpacity 的音量

Port 8081 already in use, packager is either not running or not running correctly Command /bin/sh failed with exit code 2

我们可以在 react webapp 和 react native 应用程序之间共享代码吗,并且可以在 react-native 生产环境中使用

如何在 React Native 中更改 textInput 占位符的字体系列

如何构建一个 react-native 应用程序,以便它在 ipad 上作为 ipad 应用程序运行?