繁体   English   中英

React Native View 在居中时缩小以适应内容

[英]React Native View shrinks to fit content when centered

我有一个 React Native View ,我想扩展到但不超过给定的宽度。 在这个View ,我有一个Text元素,我想填充其父元素的整个宽度。 它看起来像这样: 无对齐集

但是,如果我将父View设置为与alignSelf: 'center'居中对齐,则视图将缩小以适应Text视图内的Text ,如下所示: 中心对齐设置

为什么改变View的对齐方式会导致它改变大小,我该如何防止这种情况?

预期输出: 在此处输入图片说明

复制此场景的完整代码:

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


export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.box}>
        <Text style={styles.paragraph}>Text</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  box: {
    backgroundColor: 'red',
    height: 50,
    maxWidth:200,
    alignSelf: 'center'  // <---REMOVE THIS LINE TO FILL VIEW
  },
  paragraph: {
    textAlign: 'left',
    backgroundColor: 'green',
  },
});

为什么增加宽度不起作用

虽然设置固定width值会强制最大尺寸,但它会阻止此元素缩小到低于该值。 因此,指定width不是解决方案。 这是一个示例情况,其中视图的大小将超出显示范围。

带宽度:

在此处输入图片说明

预期的:

在此处输入图片说明

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


export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.box}>
        <Text style={styles.paragraph}>Text</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignContent:'center',//ADD THIS LINE
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  box: {
    backgroundColor: 'red',
    height: 50,
    maxWidth:200,
  },
  paragraph: {
    textAlign: 'left',
    backgroundColor: 'green',
  },
});

世博会

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM