当前位置: 首页 > 知识库问答 >
问题:

使用react native在屏幕上居中显示文本

闾丘坚诚
2023-03-14

我试图在屏幕上垂直和水平居中显示文本。这是我的密码

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>

共有2个答案

林国安
2023-03-14

我建议将标头设置为位置:'绝对',并在容器上使用flex: 1gene-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
    }
});

关于高度,你只是在高度这个词中有一个错字。

公冶才
2023-03-14

这是在屏幕中居中显示文本的一种方法:

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

您也可以尝试使用位置:“绝对”:

<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>
 类似资料:
  • 问题内容: 如何将通过javascript 函数打开的弹出窗口居中显示在屏幕变量中心,以当前选定的屏幕分辨率为中心? 问题答案: 更新:它现在也可以在尚未超出屏幕宽度和高度的窗口上运行! 如果您使用双显示器,则窗口将水平居中,而不是垂直居中…使用此功能可以解决此问题。 用法示例:

  • 问题内容: 如何使用jQuery在屏幕中央设置a ? 问题答案: 我喜欢向jQuery添加功能,因此该功能将有所帮助: 现在我们可以这样写:

  • 谁能引导我过去吗?也许我的效用不好?

  • 8.3.3 打印输出的中断功能 打印输出是一种硬拷贝输出,也是一种常用的输出形式。随着计算机应用领域的不断扩大,外围设备的重视程度也越来越高。目前,打印机的种类已日益丰富,有针式打印机、喷墨打印机和激光打印机等。从打印色彩来看,既有普通的黑色打印,也有彩色打印。总之,计算机打印输出的品质是越来越高。 1、打印机状态字 打印机状态字记录着打印机的当前工作情况(或状态),它相当于CPU中的程序状态字和

  • 问题内容: 如何在ReactNative中水平和垂直居中放置文本? 我在rnplay.org中有一个示例应用程序,其中 justifyContent =“ center” 和 alignItems =“ center” 不起作用:https : **//rnplay.org/apps/AoxNKQ** 文本应居中。为什么在文本(黄色)和父容器之间的顶部留有空白? 码: 问题答案: 从‘样式删除,和