【问题标题】:I have mentioned flex value to 0.5 but it is not working我已经提到 flex 值为 0.5 但它不起作用
【发布时间】:2021-12-02 13:39:30
【问题描述】:

我已经编写了以下代码,但我在“titleContainer”下的 flex 不起作用。

export const Focus = () => {
  return (
    <View style={styles.container}>
      <View style={styles.titleContainer}>
        <Text style={styles.title}>What would you like to focus on?</Text>
        <TextInput />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#43840',
  },
  titleContainer: {
    flex: 0.5,
    padding: 16,
    justifyContent: 'center',
    backgroundColor: '#559974',
  },
  title: {
    color: 'white',
    fontWeight: 'bold',
    fontSize: 15,
  },
});

请看屏幕截图。绿色背景应覆盖屏幕的一半。

现在解决了! 实际上这个组件是有条件地显示的。这种情况有问题。我已经解决了这个问题,一切正常。

【问题讨论】:

  • 你想要的是titleContainer占据容器50%的高度吗?
  • 是的!我想要那个。
  • 您需要将父容器设为 {display: 'flex'} 才能在子标签中使用 flex 属性。

标签: css react-native flexbox


【解决方案1】:

Flex在RN中只取整数值

如果您希望 titleContainer 使用 flex 占用 50% 的容器大小,这就是您可以实现的方法。

您需要另一个视图与 titleContainer 采用相同的 flex 值,因此 titleContainer 和该转储视图将占用父视图的 50% 大小

export const Focus = () => {
  return (
    <View style={styles.container}>
      <View style={styles.titleContainer}>
        <Text style={styles.title}>What would you like to focus on?</Text>
        <TextInput />
      </View>
      <View style={{flex: 1}} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#43840',
  },
  titleContainer: {
    flex: 1,
    padding: 16,
    justifyContent: 'center',
    backgroundColor: '#559974',
  },
  title: {
    color: 'white',
    fontWeight: 'bold',
    fontSize: 15,
  },
});

【讨论】:

  • 没有效果
  • @Developer 你是否在 titleContainer 下添加了转储视图
  • 实际上这个组件是有条件地显示的。这种情况有问题。我已经解决了这个问题,一切正常。我很快就会删除这个问题。谢谢!
【解决方案2】:

要在子标签上使用 flex 属性,您的父标签需要有一个 display: "flex" 属性。

container: {
    display: 'flex',
    flexDirection: 'column',
    flex: 1,
    backgroundColor: '#43840',
  },

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 2015-05-05
    • 2021-08-18
    • 2023-01-19
    • 2013-08-18
    • 1970-01-01
    • 2018-08-11
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多