【问题标题】:Ternary Operator React Native in StyleSheet样式表中的三元运算符 React Native
【发布时间】:2021-12-10 17:10:10
【问题描述】:

有没有办法在StyleSheet 中使用三元运算符?

目前,我的TextInput 看起来是这样的:

.tsx

<TextInput
  defaultValue={selectedEvent ? selectedEvent.title : ""}
  style={[
    styles.textInput,
    { color: colorScheme === "dark" ? "#ffffff" : "#000000" },
  ]}
  onChangeText={inputChangeHandler}
/>

样式表

const styles = StyleSheet.create({
  textInput: {
    borderBottomColor: "#ccc",
    borderBottomWidth: 1,
    marginBottom: 15,
    paddingVertical: 4,
    paddingHorizontal: 2,
  },
})

最好不要将内部和外部样式结合起来。

【问题讨论】:

    标签: css reactjs react-native tsx react-native-stylesheet


    【解决方案1】:

    试试这个: 在你 TextInput

    style={styles.textInput(colorScheme)}
    

    样式表

    textInput:(colorScheme)=> ({
      borderBottomColor: '#ccc',
      borderBottomWidth: 1,
      marginBottom: 15,
      paddingVertical: 4,
      paddingHorizontal: 2,
      color: colorScheme === "dark" ? "#ffffff" : "#000000"
    }),
    

    Snack Example

    【讨论】:

    • 魔术。看起来很有趣,支持它,并且它(部分)有效。编译器会抱怨很多,而这种技术会减少我的一些风格hmm
    • 我很感兴趣。你有这个的工作演示吗?从逻辑上讲,这是有道理的,但我无法在运行示例中验证/验证它(RN 有时非常不合逻辑)。
    • @DrewReese 当然,我已经添加了一个示例。
    • 啊,我明白了,仅适用于本机。
    • @DrewReese 是的,看起来是这样。
    【解决方案2】:

    在 StyleSheet 中不能使用三元。 但是你可以像这样结合三元和样式表:

    <div
        style={checkIfActive(props.position, 1)
            ? { ...styles.circle, ...styles.circleActive }
            : { ...styles.circle, ...styles.circleUnactive }}
    />
    

    你的 CSS 可以是:

    circle: {
        width: '80%',
        margin: 'auto',
        height: 20,
        borderRadius: 10,
        borderStyle: 'solid',
        borderWidth: 1,
        borderColor: '#ffffff83',
    },
    circleUnactive: {
        backgroundColor: '#40c5ee4e',
    },
    circleActive: {
        backgroundColor: '#40c5ee',
    },
    

    【讨论】:

      【解决方案3】:

      StyleSheet 正在生成静态样式“类”,但您可以定义要使用的亮/暗类并将其附加到数组中。不过,这与您已经完成的并没有太大的不同。

      例子:

      <TextInput
        defaultValue={selectedEvent ? selectedEvent.title : ''}
        style={[
          styles.textInput,
          styles[colorScheme === 'dark' ? 'dark' : 'light'],
        ]}
        onChangeText={console.log}
      />
      
      ...
      
      const styles = StyleSheet.create({
        ...
        textInput: {
          borderBottomColor: '#ccc',
          borderBottomWidth: 1,
          marginBottom: 15,
          paddingVertical: 4,
          paddingHorizontal: 2,
        },
        light: {
          color: '#000',
        },
        dark: {
          color: '#fff',
        },
      });
      

      这是上面代码的运行Expo Snack

      【讨论】:

        猜你喜欢
        • 2021-01-28
        • 2019-02-17
        • 2021-11-20
        • 2021-01-17
        • 1970-01-01
        • 2011-05-06
        • 2022-01-04
        • 1970-01-01
        • 2018-02-06
        相关资源
        最近更新 更多