在 React Native 中,使用 flexbox,我的<Text>
组件中的文本水平(和垂直)居中。
这按预期工作 -如果文本行足够短,不需要换行到下一行。
但是,当给定一个跨多行换行的长文本字符串时,渲染的文本不会水平居中!
相反,换行的文本与左边缘对齐。
如何强制换行的文本水平居中?
这水平居中shortText
,但不longText
:
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
class Deck extends React.Component {
render() {
const shortText = 'Centered!';
const shortText = 'This very long line of text does NOT Center. Instead the wrapped text is aligned to the left edge of the container.';
return (
<View style={styles.container}>
<View>
<Text style={styles.titleText}> {shortText} </Text>
<Text style={styles.titleText}> {longText} </Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
titleText: {
fontSize: 27,
flexWrap: 'wrap',
alignSelf: 'center',
},
});
注意:我找到了很多堆栈溢出问题/答案,以及
垂直居中和文本不换行到多行时水平居中的博客文章。
但是我一直找不到任何用于将换行到多行的居中水平文本。
另外:请注意,React Native 为文本实现了"有限样式继承",这与 css 标准略有不同。例如,<Text>
继承color
和"字体大小properties only from parent
文本components, but not
视图"组件。
此外,React Native 的 Flexbox 布局实现与 CSS 标准略有不同。
我不知道 React Native 的差异是否也会影响水平居中的换行文本。
您可以像这样设置textAlign
属性:
<Text style={{textAlign: 'center'}}>centered Text</Text>
可以在此处查看textAlign
属性的文档: https://reactnative.dev/docs/text-style-props#textalign