📅  最后修改于: 2020-12-08 06:06:22             🧑  作者: Mango
为了适应不同的屏幕尺寸,React Native提供了Flexbox支持。
我们将使用与React Native-样式一章中使用的相同的代码。我们将只更改PresentationalComponent 。
为了获得所需的布局,flexbox提供了三个主要属性-flexDirection justifyContent和alignItems 。
下表显示了可能的选项。
Property | Values | Description |
---|---|---|
flexDirection | ‘column’, ‘row’ | Used to specify if elements will be aligned vertically or horizontally. |
justifyContent | ‘center’, ‘flex-start’, ‘flex-end’, ‘space-around’, ‘space-between’ | Used to determine how should elements be distributed inside the container. |
alignItems | ‘center’, ‘flex-start’, ‘flex-end’, ‘stretched’ | Used to determine how should elements be distributed inside the container along the secondary axis (opposite of flexDirection) |
如果要垂直对齐项目并将其居中,则可以使用以下代码。
App.js
import React, { Component } from 'react'
import { View, StyleSheet } from 'react-native'
const Home = (props) => {
return (
)
}
export default Home
const styles = StyleSheet.create ({
container: {
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'grey',
height: 600
},
redbox: {
width: 100,
height: 100,
backgroundColor: 'red'
},
bluebox: {
width: 100,
height: 100,
backgroundColor: 'blue'
},
blackbox: {
width: 100,
height: 100,
backgroundColor: 'black'
},
})
输出
如果需要将项目移到右侧,并且需要在项目之间添加空格,那么我们可以使用以下代码。
App.js
import React, { Component } from 'react'
import { View, StyleSheet } from 'react-native'
const App = (props) => {
return (
)
}
export default App
const styles = StyleSheet.create ({
container: {
flexDirection: 'column',
justifyContent: 'space-between',
alignItems: 'flex-end',
backgroundColor: 'grey',
height: 600
},
redbox: {
width: 100,
height: 100,
backgroundColor: 'red'
},
bluebox: {
width: 100,
height: 100,
backgroundColor: 'blue'
},
blackbox: {
width: 100,
height: 100,
backgroundColor: 'black'
},
})