使用React Native将文本居中显示在屏幕上

17

我正在尝试在屏幕上垂直和水平居中文本。这是我的代码

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
         <Text> Header </Text>
         </View>
         <Text style={styles.text}> some text in the middle center of the screen </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
        backgroundColor:'white',
        alignItems:'center',
        justifyContent:'center'
    },
     header: {
        backgroundColor: 'green',
        alignSelf: 'stretch',
        alignItems: 'center',
        heigth: 80 // this dose not change the header height
    },
  text:{
      //flex: 1,
      justifyContent:'center',
  }
});

如果我在文本中添加flex:1,标题也会居中,这不是预期的结果。我不知道是否相关,但我也无法修改标题视图的高度。我该如何解决这个问题?问题可以在此示例中重现。

<div data-snack-id="S1urACbJM" data-snack-platform="ios" data-snack-preview="true" data-snack-theme="light" style="overflow:hidden;background:#fafafa;border:1px solid rgba(0,0,0,.16);border-radius:4px;height:505px;width:100%"></div>
<script async src="https://snack.expo.io/embed.js"></script>

3个回答

33

以下是一种将文本居中在屏幕上的方法:

<View style={{
    flex: 1, 
    alignItems: 'center',
    justifyContent: 'center', 
    backgroundColor: 'blue'
}}>
    <Text style={{backgroundColor: 'red'}}>
        Your Text
    </Text>
</View>

你也可以尝试使用position:'absolute':

<View style={{
    backgroundColor: 'blue',
    position: 'absolute', 
    top: 0, left: 0, 
    right: 0, bottom: 0, 
    justifyContent: 'center', 
    alignItems: 'center'}}>
<Text style={{backgroundColor: 'red'}}> Your Text </Text>
</View>

居中对齐的文本


5
我建议将头部设置为position:'absolute',并在容器上使用flex:1justify-content:'center'。请检查已更新的样式。
const styles = StyleSheet.create({
  container: {
        backgroundColor:'white',
        alignItems:'center',
        justifyContent:'center',
        flex:1,
        paddingTop:20 //this amount should be equal to the header height so that any items displayed inside the container will start after the absolute positioned header
    },
     header: {
        backgroundColor: 'green',
        alignSelf: 'center',
        justifyContent:"flex-start",
        alignItems: 'center',
        position:"absolute",
        top:0
    }
});

关于高度,您刚才在单词height中打了一个错字。


0
我尝试了上述的解决方案,我意识到我的父元素的大小并没有因为其他样式的冲突而与屏幕大小相等。所以,我通过将视图的高度设置为手机屏幕的高度来解决了这个问题。
import { ActivityIndicator, Dimensions, View } from 'react-native';

<View style={{height: windowHeight * 0.8, flex: 1, alignItems: 'center', justifyContent: "center", borderWidth: 1,}}>
  <View>
    <ActivityIndicator animating size={100} color="green" />
    <Text>Loading</Text>

  </View>
</View>

你可以把它放在任何地方。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接