【问题标题】:Grid Layout of View in React NativeReact Native 中 View 的网格布局
【发布时间】:2018-01-27 22:44:06
【问题描述】:

我正在尝试使用这样的布局创建一个 React Native 视图。如何创建一个盒子,就像图片上的其中一个盒子一样?

是否可以使用 Flex 实现这一目标?我需要一个用于数字(左),一个用于文本(右,上)和另一个文本(右,下)?它们应该与图像上的顺序相同。

【问题讨论】:

  • 试一试,看看会发生什么。
  • Flex 应该可以解决数字和文本容器的问题。然后,文本容器可以像平常一样保存text block

标签: android css reactjs react-native flexbox


【解决方案1】:

我建议你学习 flexbox 样式规则。

设计这样简单的屏幕会让你的生活更轻松。

您的渲染方法应如下所示:

render() {
    return (
        <View style={styles.containerStyle}>
            <Text style={styles.numberStyle}>6</Text>
            <View style={styles.textContainerStyle}>
                <Text>D in 227 -</Text>
                <Text>Vtr. Online Lehrer</Text>
            </View>
        </View>
    );
}

您的样式应如下所示:

const styles = {
    containerStyle: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'space-around'
    },
    numberStyle: {
        flex: 1
    },
    textContainerStyle: {
        flex: 4,
        flexDirection: 'row',
        justifyContent: 'center' 
    }
}

注意:我没有测试输出,但它应该可以工作。如果它没有按预期工作,请随时问我。

你可以在这里学习 flexbox:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

上面的链接是针对 css 的,但是如果你学会了,那么你可以在 React Native 中进行类似的应用。

【讨论】:

    【解决方案2】:

    您需要注意两个属性才能使您的文本在视图中心对齐。

    第一个是 justifyContent,第二个是 alignItems。你需要在你的样式对象中使用这些属性来让文本标签移动到视图的中心。

    您必须执行justifyContent: 'flex-end' 之类的操作。通常这用于垂直位置。我们可以给justifyContent'flex-end' 将您的文本框一直向下推。 'center' 当然会把你的文本框放在中间。

    还有justifyContent:'flex-start'。这就好像你根本没有提供任何属性,所以不需要使用这个。

    第二个属性是alignItems,其值与justifyContent 相同。所以justifyContent 用于垂直对齐,alignItems 用于水平对齐。

    所以它看起来像这样:

    // Import a library to help create a component
    import React from 'react';
    import { Text, View } from 'react-native';
    
    // Make a component
    const Header = (props) => {
      const { textStyle, viewStyle } = styles;
    
      return (
        <View style={viewStyle}>
          <Text style={textStyle}>{props.headerText}</Text>
        </View>
      );
    };
    
    const styles = {
      viewStyle: {
        backgroundColor: '#F8F8F8',
        justifyContent: 'center',
        alignItems: 'center',
        height: 60
      },
      textStyle: {
        fontSize: 20
      }
    };
    
    // Make the component available to other parts of the app
    export default Header;
    

    【讨论】:

      猜你喜欢
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-11
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多