React Native 样式表的基础知识

在 React Native 中我们要使用组件元素进行样式设置的话,我们需要使用StyleSheet组件才能制定样式。useColorScheme是为 APP 定义颜色主题的。在此笔记中我们只是简单做一个介绍和使用。

使用StyleSheet定义样式

当我们要使用StyleSheet的话,我们需要引入对应模块,并且使用create关键字进行样式对象创建。在 React Native 中布局方式采用的只有Flex布局方式,Flex 布局方式跟 CSS3 中的 Flex 布局一致。

我们在第一章节中笔记中已经写好了一个Hello World的程序,我们可以再这个基础上进行样式的添加,具体代码如下:

<View style={
    
    style.container}>
  <Text>Hello World !</Text>
</View>
const style = StyleSheet.create({
    
    
  container: {
    
    
    display: "flex",
    flex: 1,
    justifyContent: "center",
  },
});

注意:SafeAreaView标签内的元素不能设置样式,这样会导致错误。

useColorScheme 颜色主题

useColorScheme是专门用于配色方案更新的 Hook。返回值表示当前用户首选的配色方案。具体的例子如下:

import React from "react";
import {
    
     Text, View, StyleSheet, useColorScheme } from "react-native";

const App: React.FC = () => {
    
    
  const colorScheme = useColorScheme() === "dark";

  return (
    <View style={
    
    style.container}>
      <Text style={
    
    colorScheme ? style.whiteText : style.blackText}>
        Hello World !
      </Text>
    </View>
  );
};

const style = StyleSheet.create({
    
    
  container: {
    
    
    display: "flex",
    flex: 1,
    justifyContent: "center",
  },
  whiteText: {
    
    
    color: "#FFFFFF",
  },
  blackText: {
    
    
    color: "#000000",
  },
});

export default App;

猜你喜欢

转载自blog.csdn.net/qq_33003143/article/details/132136961