将本地文本置于屏幕中心

use*_*567 8 reactjs react-native

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

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',
  }
});
Run Code Online (Sandbox Code Playgroud)

如果我将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>
Run Code Online (Sandbox Code Playgroud)

Her*_*rio 10

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

<View style={{
    flex: 1, 
    alignItems: 'center',
    justifyContent: 'center', 
    backgroundColor: 'blue'
}}>
    <Text style={{backgroundColor: 'red'}}>
        Your Text
    </Text>
</View>
Run Code Online (Sandbox Code Playgroud)

你也可以尝试使用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>
Run Code Online (Sandbox Code Playgroud)

你的中心文字


Amr*_*bib 5

我建议将标题设置为position:'absolute', 并在容器上使用flex:1和justify-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
    }
});
Run Code Online (Sandbox Code Playgroud)

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