Layout 概念

Mobile 佈局遇到的問題

Layout 原則

  • 若要全螢幕或是item要跟螢幕等寬或高,盡量避免寫定width, height 的單位值,而是利用percentage 或 flex 的方式

const styles = StyleSheet.create({
    fullscreen: {
        width: 640,
        height: 960
    }
})
  • 除非動態的style值,盡量避免在 style 中放置未經styleSheet 建立的物件

render(){
  return (
    <View style={ { width: 600, height: 600 } }>
  )
}
  • 將版面與顏色+字型大小分離,方便重複利用

const styles = StyleSheet.create({
    title: {
        fontSize: 22,
        color: 'white'
    },
    subTitle: {
        color: 'red'
    },
    text: {
        marginHorizontal: 20,
    }
})

...

render(){
    return (
        <View>
            <Text style={[styles.title, styles.text]}>{'Hello world'}></Text>
            <Text style={[styles.subTitle, styles.text]}>{'my name is react-native'}></Text>
        </View>
    )
}

常用Flexbox 設定值

  • Primary and secondary axis

    • Column 的主軸為Vertical 所以設定justify-content: 'center'會是垂直置中

    • Row 的主軸為Horizontal 所以設定justify-content: 'center'會是水平置中

  • flexDirection: 'column'

  • flexDirection: 'row'

  • justifyContent: 'flex-start|center|flex-end'

  • alignItems: 'flex-start|center|flex-end'

  • alignSelf: 'flex-start|center|flex-end'

  • flex: 1

把畫面撐開與 parent 同高

ReactNative 預設Flexbox的direction 為 column

parent 的 flexDirection 為 column

parent 的 flexDirection 為 row時

child 設置flex: 1 把高度撐得parent同高

flex: 1 把寬度撐得與parent 同寬

Last updated