如果在 React Native 中禁用对象,如何保持样式?

how to keep the style if disable objects in react native?

我正在尝试构建我的问题:
我在做什么: 我正在尝试在 react-native (typescript) 中创建一个开放时间视图,您可以在其中打开和关闭工作日。对于开放的日子,您可以通过时间选择器设置开放时间。就像您在此处看到的 Google 之一:Google Opening hours


我的问题是什么:我运行现在遇到了样式问题。当我关闭一天时,整个内容会跳到右边。我应该如何构造和设计我的组件?

My Opening Hours View


这是我的代码
interface Props {
  day: String;
}

export function OpenTimesItem(props: Props) {
  const [isOn, setOn] = useState(true);
  const toggleOn = () => setOn(!isOn);

  return (
    <View style={styles.dayContainer}>
      <Text>{props.day}</Text>
      <View>
        <Switch value={isOn} onValueChange={toggleOn} />
        <Text>{isOn ? "Geöffnet" : "Geschlossen"}</Text>
      </View>
      {isOn ? (
        <View style={styles.timePicker}>
          <TimePicker />
          <Text>-</Text>
          <TimePicker />
        </View>
      ) : (
        <View style={styles.timePicker}></View>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  dayContainer: {
    borderBottomWidth: 1,
    borderBottomColor: "#D1D1D1",
    alignItems: "center",
    justifyContent: "space-between",
    flexDirection: "row",
  },
  timePicker: {
    flexDirection: "row",
    alignItems: "center",
  },
});

您可以使用 flex: 1flex-end 来实现您想要的。请注意,我没有您的 TimePicker 组件,因此我添加了一个虚拟文本组件。

import React, { useState } from "react"
import { StyleSheet, Switch, Text, View } from "react-native"

interface Props {
  day: String
}

export function OpenTimesItem(props: Props) {
  const [isOn, setOn] = useState(true)
  const toggleOn = () => setOn(!isOn)

  return (
    <View style={styles.dayContainer}>
      <Text style={styles.flex1}>{props.day}</Text>
      <View style={[styles.flex1, { alignItems: "center" }]}>
        <Switch value={isOn} onValueChange={toggleOn} />
        <Text>{isOn ? "Geöffnet" : "Geschlossen"}</Text>
        <View style={styles.timePicker} />
      </View>
      <View style={styles.flex1}>
        {isOn && (
          <View style={{ flexDirection: "row", alignSelf: "flex-end" }}>
            <Text>10:22</Text>
            <Text>-</Text>
            <Text>10:25</Text>
          </View>
        )}
      </View>
    </View>
  )
}

const styles = StyleSheet.create({
  dayContainer: {
    borderBottomWidth: 1,
    borderBottomColor: "#D1D1D1",
    alignItems: "center",
    justifyContent: "space-between",
    flexDirection: "row",
  },
  timePicker: {
    flexDirection: "row",
    alignItems: "center",
  },
  flex1: {
    flex: 1,
  },
})

这会产生以下结果。