RN中的StyleSheet
一、RN中样式的特点
RN的样式和前端的CSS的样式有一些区别。主要如下:
RN中的样式 | 前端的CSS | |
---|---|---|
继承性 | 没有继承性 | 有继承性 |
命名 | fontSize(小驼峰命名) | font-size |
尺寸单位 | with: 100 | With: 100px |
特殊的样式名 | marginHorizontal(水平外边距)、 marginVertical(垂直外边距) |
二、声明方式
1、通过组件的style属性直接声明
当属性值为对象或者数组时,如下示例:
属性值为对象:<Text style={ {样式} }/>
属性值为数组:<Text style={ [{样式1}, {样式2}, {样式3},..., {样式n}] }/>
2、使用StyleSheet声明的样式
在组件里使用StyleSheet声明的样式,按照以下三步即可:
引入StyleSheet: import { StyleSheet, View} from 'react-native'
声明样式:const myStyle = StyleSheet.create({foot: {样式1}, bar: {样式2}})
使用样式:<View style={ [ myStyle.foot, myStyle.bar]} > 显示内容 </View>
三、 实例代码
入口文件App.tsx
import {View} from 'react-native'
import React from 'react'
import Index from './src/stylesheet'const App = () => {return (<View><Index /></View>)
}export default App
stylesheet目录下的index.tsx文件
import {StyleSheet, Text, View} from 'react-native'
import React from 'react'const index = () => {return (<View><Text style={{fontSize: 20, color: 'red'}}>红色</Text><Text style={[{fontSize: 20, color: 'red'}, {fontSize: 20, color: 'green'}]}>绿色覆盖红色</Text><Text style={[styles.text1]}>黄色</Text><Text style={[styles.text1, styles.text2]}>蓝色覆盖黄色</Text></View>)
}export default indexconst styles = StyleSheet.create({text1: {fontSize: 30,fontWeight: 'bold',color: 'yellow',},text2: {fontSize: 30,fontWeight: 'bold',color: 'blue',},
})
这里需要提示一下,直接在style属性声明的方式,虽然也可以实现效果,但是推荐使用stylesheet。如果style属性值是一个数组,后面对象里的设置会覆盖前面对象里相同的设置。