Flex未在react native中平均拆分组件

hfyxw5xn  于 2022-11-30  发布在  React
关注(0)|答案(1)|浏览(78)

我试着做一个这样的布局:

为此,我创建了两个组件,分别命名为HalfWidthFullHeightCardHalfWithHalfHeightCard
我已经创建了HalfWidthFullHeightCell组件,作为?

<TouchableOpacity onPress={pressEvent}>
            <ImageBackground
                source={sourcePath}
                imageStyle={{ borderRadius: 8, resizeMode: 'cover', width: '100%' }}
                style={styles.halfWidthCard}>
                <Text style={styles.halfWidthCardHeading}>{heading}</Text>
                <Text style={styles.halfWidthCardText}>{cardText}</Text>
            </ImageBackground>
        </TouchableOpacity>
...
    halfWidthCard: {
        backgroundColor: colors.brightYellow,
        marginBottom: 10,
        borderRadius: 8,
    },

根据cardText,卡片的宽度会自动计算,而在halfWidthCardText样式表中,我只有padding: 10
接下来,对于HalfWithHalfHeightCard,除了样式之外,其他一切都是相同的:

...

    smallHalfWidthCard: {
        backgroundColor: colors.brightYellow,
        borderRadius: 8,
        marginBottom: 10
    },
    smallHalfWidthCardHeading: {
        padding: 10,
    },
    smallHalfWidthCardText: {
        padding: 10,
    },

我把这两个部分放在一起,我在做:

<ScrollView contentContainerStyle={{padding: 15}}>
    <View style={{flexDirection: 'row',}}>
                <HalfWidthFullHeightCell />
                <View>
                    <HalfWithHalfHeightCell />
                    <HalfWithHalfHeightCell />
                </View>
    </View>
</ScrollView>

现在有两个问题:

1.将灰色区域视为设备的宽度。HalfWidthFullHeightCard占用100%的空间,

  1. HalfWithHalfHeightCard位于屏幕之外,并且与HalfWidthFullHeightCard的高度不同。
    那么,我如何使这些组件变得灵活,以便它们能够随着屏幕尺寸的变化而适应布局呢?
kpbpu008

kpbpu0081#

我会把它做成这样

import * as React from 'react';
import { Text, View, StyleSheet, Dimensions } from 'react-native';

const ScreenWidth = Dimensions.get('window').width;

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.WholeBox}>
        <View style={styles.Block}></View>
        <View style={{ flex: 1 }}>
          <View style={styles.Block}></View>
          <View style={styles.Block}></View>
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
  },
  WholeBox: {
    width: ScreenWidth,
    height: 300,
    flexDirection: 'row',
  },
  Block: {
    flex: 1,
    backgroundColor: '#DDA73A',
    margin: 6,
    borderRadius: 8,
  },
});

Working Example Here

相关问题