首页 > 解决方案 > React Native:视图不覆盖父高度

问题描述

问题

有 2 个选项卡水平堆叠,在第一个选项卡中,当两个选项卡中的内容不同时,绿色视图无法填充父级的高度。

在此处输入图像描述

世博会重现

https://snack.expo.dev/@vinay-sharma/92706e

代码

import React from "react";
import { Text, View } from "react-native";

const Tab = ({ textNodes }) => {
  return (
    <View style={{ flex: 1, backgroundColor: "red" }}>
      <View style={{ flexDirection: "row" }}>
        <View style={{ backgroundColor: "blue", width: 10 }}></View>

        {/* the green view isn’t able to fill parent's height*/}
        <View style={{ backgroundColor: "green", flex: 1 }}>
          {textNodes.map((node) => (
            <Text>{node}</Text>
          ))}
        </View>
      </View>

      <View style={{ height: 10, backgroundColor: "black" }} />
    </View>
  );
};

export default function App() {
  return (
    <View style={{ flexDirection: "row", marginTop: 25 }}>
      <Tab textNodes={[1, 2, 3]} />
      <Tab textNodes={[1, 2, 3, 4]} />
    </View>
  );
}

标签: javascriptcssreactjsreact-nativeflexbox

解决方案


Just add style property height: '100%' in the row view in your Tab() function

The first element is not taking 100% of the height because it has less Childs (default behaviour of a View, doc)

import React from 'react';
import { Text, View } from 'react-native';

const Tab = ({ textNodes }) => {
  return (
    <View style={{ flex: 1, backgroundColor: 'red' }}>
      <View style={{ flexDirection: 'row', height: '100%' }}> //here add height 100%
        <View style={{ backgroundColor: 'blue', width: 10 }}></View>

        {/* the green view isn’t able to fill parent's height*/}
        <View style={{ backgroundColor: 'green', flex: 1 }}>
          {textNodes.map((node)=><Text>{node}</Text>)}
        </View>
      </View>

      <View style={{ height: 10, backgroundColor: "black" }} />
    </View>
  )
}

export default function App() {
  return (
    <View style={{ flexDirection: 'row', marginTop: 25 }}>
      <Tab textNodes={[1, 2, 3]} />
      <Tab textNodes={[1, 2, 3, 4]} />
    </View>
  );
}

推荐阅读