ReactNative——样式语法

104 阅读1分钟

StyleSheet

  • 没有继承性
    • RN 中的继承只发生在 Text 组件上
  • 样式名采用小驼峰命名
    • fontSize VS font-size
  • 所有尺寸都是没有单位
    • width: 100
  • 有些特殊的样式名
    • marginHorizontal(水平外边距), marginVertical(垂直外边距)

RN样式声明方式

  • 通过 style 属性直接声明

    • 属性值为对象:<组件 style={{样式}}/>
    • 属性值为数组:<组件 style={[{样式 1},..., {样式 N}]} />
  • 在 style 属性中调用 StyleSheet 声明的样式

    • 引入:import {StyleSheet, View} from'react-native'
    • 声明:const styles = StyleSheet.create({foo:{样式 1}, bar:{样式 2}})
    • 使用:<View style={[styles.foo, styles.bar]}> 内容</View>
import React, { Component } from'react'
import { Text, StyleSheet, View } from'react-native'

export default class App extends Component {
  render() {
    return (
      <View style={{
        marginHorizontal: 20,
        backgroundColor: '#dfb'
      }}>
        <Text style={[styles.red, styles.fontLarge]}>Hello RN</Text>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  red: {
    color: '#e33'
  },
  fontLarge: {
    fontSize: 40,
  }
})

FlexBox

  • 在 web 中的 flex 布局

image.png

  • 在 RN 中
  1. 默认主轴是垂直的,交叉轴水平

image.png

  1. Flexbox – 属性
  • flexDirection
    • 声明主轴方向: row(Web 默认) | column(RN 默认)

image.png

  • justifyContent
    • 声明项目在主轴上的对齐方式
  • alignItems
    • 声明项目在交叉轴上的对齐方式
  • flex
    • 声明项目在主轴上的尺寸比例

响应式布局

  • Flexbox
  • Dimensions
// 获取屏幕宽度、高度
import { Dimensions } from'react-native';
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;