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

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

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

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

  1. <TouchableOpacity onPress={pressEvent}>
  2. <ImageBackground
  3. source={sourcePath}
  4. imageStyle={{ borderRadius: 8, resizeMode: 'cover', width: '100%' }}
  5. style={styles.halfWidthCard}>
  6. <Text style={styles.halfWidthCardHeading}>{heading}</Text>
  7. <Text style={styles.halfWidthCardText}>{cardText}</Text>
  8. </ImageBackground>
  9. </TouchableOpacity>
  10. ...
  11. halfWidthCard: {
  12. backgroundColor: colors.brightYellow,
  13. marginBottom: 10,
  14. borderRadius: 8,
  15. },

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

  1. ...
  2. smallHalfWidthCard: {
  3. backgroundColor: colors.brightYellow,
  4. borderRadius: 8,
  5. marginBottom: 10
  6. },
  7. smallHalfWidthCardHeading: {
  8. padding: 10,
  9. },
  10. smallHalfWidthCardText: {
  11. padding: 10,
  12. },

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

  1. <ScrollView contentContainerStyle={{padding: 15}}>
  2. <View style={{flexDirection: 'row',}}>
  3. <HalfWidthFullHeightCell />
  4. <View>
  5. <HalfWithHalfHeightCell />
  6. <HalfWithHalfHeightCell />
  7. </View>
  8. </View>
  9. </ScrollView>

现在有两个问题:

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

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

kpbpu0081#

我会把它做成这样

  1. import * as React from 'react';
  2. import { Text, View, StyleSheet, Dimensions } from 'react-native';
  3. const ScreenWidth = Dimensions.get('window').width;
  4. export default function App() {
  5. return (
  6. <View style={styles.container}>
  7. <View style={styles.WholeBox}>
  8. <View style={styles.Block}></View>
  9. <View style={{ flex: 1 }}>
  10. <View style={styles.Block}></View>
  11. <View style={styles.Block}></View>
  12. </View>
  13. </View>
  14. </View>
  15. );
  16. }
  17. const styles = StyleSheet.create({
  18. container: {
  19. flex: 1,
  20. justifyContent: 'center',
  21. backgroundColor: '#ecf0f1',
  22. },
  23. WholeBox: {
  24. width: ScreenWidth,
  25. height: 300,
  26. flexDirection: 'row',
  27. },
  28. Block: {
  29. flex: 1,
  30. backgroundColor: '#DDA73A',
  31. margin: 6,
  32. borderRadius: 8,
  33. },
  34. });

Working Example Here

展开查看全部

相关问题