【问题标题】:CSS with ternary operator - only set property in one case带有三元运算符的 CSS - 仅在一种情况下设置属性
【发布时间】:2023-04-06 04:35:02
【问题描述】:

我在我的 CSS 中使用 react native Platform API 作为三元运算符。

比如我在设置高度:

height: Platform.OS === 'ios' ? 40 : 50,

但有时我想在一种情况下设置属性,但在另一种情况下却不想:

height: Platform.OS === 'ios' ? 40 : <Don't set height>

实现这一点的正确逻辑是什么?

【问题讨论】:

    标签: javascript css react-native


    【解决方案1】:

    你可以写另一个三元运算符,如下所示

    height: Platform.OS === 'ios' ? 40 : Platform.OS === 'android' ? 50 : 0
    

    【讨论】:

      【解决方案2】:

      如果您不想设置显式值,您可以:

      1) 仅有条件地添加高度属性:

      if (Platform.OS === 'ios') {
        styles.height = 40;
      }
      

      2) 使用未定义的值:

      height: Platform.OS === 'ios' ? 40 : undefined,
      

      【讨论】:

        【解决方案3】:

        我使用的方法是制作 2 个样式组件:

        const styles = StyleSheet.create({
          withHeight: {
            color: 'red',
        height:40
          },
        withoutHeight:{
        color:'red'
        }
        });
        

        所以在你的组件中你可以这样做:

        <View style={Platform.OS =='ios'?styles.withHeight:styles.withoutheight}>
        

        希望对您有所帮助。如有疑问,请随意

        【讨论】:

        • 非常感谢,但架构是样式在一个文件中,所以我必须在样式中以某种方式在 ios 或 android 之间进行选择
        • 如果样式是另一个文件有什么问题?即使我编写了样式和代码不同的代码,这里的样式您只是根据平台选择正确的样式
        猜你喜欢
        • 2021-09-11
        • 2020-07-02
        • 1970-01-01
        • 2013-04-28
        • 2018-01-03
        • 1970-01-01
        • 2015-06-05
        • 2018-05-12
        • 1970-01-01
        相关资源
        最近更新 更多