【问题标题】:React Native- Set the height of View same as the contentReact Native - 将 View 的高度设置为与内容相同
【发布时间】:2019-04-15 10:48:28
【问题描述】:

我有一个父容器 View 有两个子容器 ViewsflexDirection: row

一个孩子View的高度大于另一个child视图的高度,因为它有内容。

我想做什么?

我想在其中一个高度较短的子视图中放置一个垂直居中的文本。在下面的示例中,文本“BUDGET”应位于旁边的图像的中心。

这里是我的问题的小吃链接。

https://snack.expo.io/ByWT6Cb5V

但问题是,如果我这样做 alignSelf: center,react native 会考虑较大子视图的高度,并根据该上下文将文本居中

P.S marginTop 为我完成了这项工作,但我觉得这是一种解决方法。

我真正的问题是,为什么内容较少的 View 的高度与其兄弟 View 的高度相同?

【问题讨论】:

    标签: reactjs react-native flexbox


    【解决方案1】:

    实际上我不明白你说的问题((在下面的示例中,文本“BUDGET”应该位于旁边图像的中心。))如果你想在一个图片,例如你说的在中间部分显示“BUDGET”,你应该使用图片背景:

    import * as React from 'react';
    import { Text, View, StyleSheet, Image,ImageBackground } from 'react-native';
    import { Constants } from 'expo';
    
    // You can import from local files
    //import AssetExample from './components/AssetExample';
    
    // or any pure javascript modules available in npm
    // import { Card } from 'react-native-paper';
    
    export default class App extends React.Component {
      render() {
        return (
          <View style={{flex:1, marginTop:100}}>
                <View style={styles.budgetBlock}>
                                <View style={styles.budgetTextBlock}>
                                    <ImageBackground source={require('./assets/snack-icon.png')} style={{width:50, height:50,justifyContent:'center',alignItems:'center'}} >
                                    <Text style={styles.budgetText}> BUDGET </Text>
    </ImageBackground>
                                </View>
                                <View style={styles.budgetValueBlock}>
                                        <Text style={styles.budgetType}> Too High </Text>
                                        <Text style={styles.budgetType}> Too High</Text>
                                        <Text style={styles.budgetType}> Too High</Text>
                                        <Text style={styles.budgetType}> Too High</Text>
                                </View>
                            </View>
            </View>
        );
      }
    }
    

    但是,如果您不是故意的,并且您“居中”的目的是垂直对齐。你应该这样做:

     budgetTextBlock: {
        flexDirection: 'row',
        alignItems: 'center',<<<<<<this shows BUDGET in center
        height: 'auto',
    
    }
    

    【讨论】:

    • 这不行,我在问题里是这么说的
    • 我确实在您的在线snack.expo 上测试了第二个,预算的地方来到了中心......
    • 来到图像的中心?你能保存零食并分享链接吗?
    猜你喜欢
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 2011-10-04
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多