[英]Center a text in the screen with react native
I am trying to center a text vertically and horizontally on the screen. 我试图在屏幕上垂直和水平居中文本。 This is my code
这是我的代码
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',
}
});
If I add the flex:1 to text, the header will also be centered which is not expected. 如果我将flex:1添加到文本中,标题也将居中,这是不期望的。 I don't know if it's related but the I am also not able to modify the header view height.
我不知道它是否相关,但我也无法修改标题视图高度。 How can I solve this?
我怎么解决这个问题? The problems can be reproduced on this snack .
这个小吃可以重现这些问题。
<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>
This is one way to center text in the screen: 这是在屏幕中居中文本的一种方法:
<View style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'blue'
}}>
<Text style={{backgroundColor: 'red'}}>
Your Text
</Text>
</View>
And you can also try with position:'absolute': 你也可以尝试使用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>
I suggest setting the header as position:'absolute'
, and use flex:1
and justify-content:'center'
on the container. 我建议将标题设置为
position:'absolute'
,并在容器上使用flex:1
和justify-content:'center'
。
Check the updated style 检查更新的样式
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
}
});
Regarding the height you just have a typo in the word height
关于身高,你只是在单词
height
有一个拼写错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.