[英]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.