React Native【实用教程】(含图标方案,常用第三库,动画,内置组件,内置Hooks,内置API,自定义组件,创建项目等)

搭建开发环境,创建启动项目

https://blog.csdn.net/weixin_41192489/article/details/147728955

样式

  • 默认的 font-size 是 14

  • 安卓中 font-weight 只支持 normal 和 bold ,而 IOS 中都支持

  • padding 的定义方式

    c 复制代码
    <View style={{ paddingTop: 10, paddingBottom: 10, paddingLeft: 20, paddingRight: 20 }}>
      {/* 内容 */}
    </View>
    
    // 或使用简写属性
    <View style={{ paddingHorizontal: 20, paddingVertical: 10 }}>
      {/* 内容 */}
    </View>

注意事项

  • 不支持百分比布局(应用 flex 布局)

  • 绝对单位需省略(不能写 px ,rem 等绝对单位)

    c 复制代码
    <View style={{ width: 100, height: 50 }} />
    // 相当于 width: 100dp (Android) 或 width: 100pt (iOS)

内联样式

html 复制代码
<Text style={{color: 'red',fontWeight: 'bold'}}>标题</Text>

【推荐】样式表

样式表比内联样式性能更高

  • 通过 StyleSheet.create 创建
  • 在组件上,给 style 属性赋值,支持数组的形式添加多个
c 复制代码
import { StyleSheet, Text } from 'react-native';
export default function HomeScreen() {
  return (
       <Text style={[styles.red,styles.bold]}>标题</Text>
  );
}
const styles = StyleSheet.create({
  red: {
    color: 'red',
  },
  bold: {
    fontWeight: 'bold',
  },
});

3D 变换 transform

c 复制代码
const styles = StyleSheet.create({
  box: {
    width: 100,
    height: 100,
    backgroundColor: 'blue',
    transformStyle: 'preserve-3d', // 保持 3D 变换
    transform: [
      { rotate: '45deg' },       // 旋转
      { scale: 1.5 },            // 缩放
    ],
  },
});
c 复制代码
{ rotate: '45deg' }         // 顺时针旋转 45 度
{ rotateX: '45deg' }        // 绕 X 轴旋转(3D 效果)
{ rotateY: '45deg' }        // 绕 Y 轴旋转(3D 效果)
{ rotateZ: '45deg' }        // 绕 Z 轴旋转(等同于 rotate)
c 复制代码
{ scale: 1.5 }              // 等比放大 1.5 倍
{ scaleX: 2 }               // 水平方向放大 2 倍
{ scaleY: 0.5 }             // 垂直方向缩小 50%
c 复制代码
{ translateX: 50 }          // 向右平移 50 像素
{ translateY: -50 }         // 向上平移 50 像素
{ translateZ: 100 }         // 向 Z 轴平移(3D 效果)
c 复制代码
{ skewX: '30deg' }          // 水平倾斜 30 度
{ skewY: '30deg' }          // 垂直倾斜 30 度

图标

Expo 的 React Native 项目中内置了@expo/vector-icons,可直接使用

搜索图标: https://icons.expo.fyi/Index


复制到项目中使用即可,如

c 复制代码
import Entypo from '@expo/vector-icons/Entypo';
c 复制代码
<Entypo name="home" size={24} color="black" />

内置组件

https://blog.csdn.net/weixin_41192489/article/details/148612134

获取元素最终渲染的宽高和位置信息

使用 onLayout (仅内置组件可用)

c 复制代码
      <View
        style={{ width: 100, height: 200, backgroundColor: "red" }}
        onLayout={(e) => {
          // 获取元素最终渲染的宽高和位置信息 {"height": 200, "width": 100.19047546386719, "x": 0, "y": 0}
          console.log(e.nativeEvent);
        }}
      ></View>

自定义组件

components/userInfo.tsx

c 复制代码
import { Text } from "react-native";
function levelView(level: number) {
  return <Text>等级:{level}</Text>;
}
export function UserInfoView({ name, level }: { name: string; level: number }) {
  return (
    <Text>
      用户名:{name}
      {levelView(level)}
    </Text>
  );
}

导入使用

c 复制代码
import { UserInfoView } from "@/components/userInfo";
c 复制代码
<UserInfoView name="朝阳" level={1} />

支持直接传 JSX

见 moreInfo

c 复制代码
  const moreInfo = () => {
    return <Text>兴趣爱好:编程</Text>;
  };
  return <UserInfoView name="朝阳" level={1} moreInfo={moreInfo()} />;
c 复制代码
export function UserInfoView({
  name,
  level,
  moreInfo,
}: {
  name: string;
  level: number;
  moreInfo?: React.ReactNode;
}) {
  return (
    <Text>
      用户名:{name}
      {levelView(level)}
      {moreInfo}
    </Text>
  );
}

子元素作为 children 传递

见 "可以"

c 复制代码
<UserInfoView>可以</UserInfoView>

components/userInfo.tsx

c 复制代码
import React from "react";
import { Text } from "react-native";
export function UserInfoView({ children }: { children?: React.ReactNode }) {
  return <Text>{children}</Text>;
}

内置 Hooks

获取页面元素 useRef

c 复制代码
import { useRef } from "react";
import { View } from "react-native";
export default function HomeScreen() {
  const viewRef = useRef(null);
  console.log(viewRef.current);
  return (
    <>
      <View
        ref={viewRef}
        style={{ width: 100, height: 200, backgroundColor: "red" }}
      ></View>
    </>
  );
}

其中 viewRef.current 中常用的属性和方法为:

  1. measure : 一个方法,用于获取视图相对于父视图的位置和尺寸。
  2. measureInWindow : 一个方法,用于获取视图相对于窗口的位置和尺寸。
  3. measureLayout : 一个方法,用于获取视图相对于另一个视图的位置和尺寸。
  4. focus : 一个方法,用于将焦点设置到视图上(如果视图支持焦点)。
  5. blur : 一个方法,用于移除视图上的焦点(如果视图支持焦点)。

获取屏幕信息 useWindowDimensions

  • width:number 类型,代表相应尺寸的宽度,单位是与设备像素无关的逻辑像素点。
  • height:number 类型,代表相应尺寸的高度,单位是与设备像素无关的逻辑像素点。
  • scale:number 类型,是设备的像素密度,即物理像素与逻辑像素的比例。
  • fontScale:number 类型,是设备的字体缩放比例因子,用于调整字体大小。
c 复制代码
import { Text, useWindowDimensions } from "react-native";
export default function HomeScreen() {
  const { width, height,scale, fontScale } = useWindowDimensions();
  return (
    <>
      <Text> 手机屏幕宽度: {width}</Text>
      <Text> 手机屏幕高度: {height}</Text>
      <Text> 手机屏幕像素密度: {scale}</Text>
      <Text> 手机屏幕字体缩放比例因子: {fontScale}</Text>
    </>
  );
}

获取手机颜色主题 useColorScheme

默认值为 linght

c 复制代码
import { Text, useColorScheme } from "react-native";
export default function HomeScreen() {
  const colorScheme = useColorScheme();
  return (
    <>
      <Text>{colorScheme}</Text>
    </>
  );
}

在手机设置中进行切换后,值变成 dark

支持的事件

点击和长按

c 复制代码
<Text 
  onPress={() => console.log('文本被点击')}
  onLongPress={() => console.log('文本被长按')}
>
  可点击的文本
</Text>

内置 API

https://blog.csdn.net/weixin_41192489/article/details/148768432

动画

https://blog.csdn.net/weixin_41192489/article/details/148785741

更多用法

原生方式修改属性 setNativeProps

在性能瓶颈/需要页面立马更新时使用,用得少

c 复制代码
  const viewRef = useRef<View>(null);
  if (viewRef.current) {
    viewRef.current.setNativeProps({
      style: {
        backgroundColor: "blue",
      },
    });
  }

常用第三方库

生成唯一 id

c 复制代码
npm i react-native-get-random-values
npm i uuid

使用

utils/UUID.ts

c 复制代码
import "react-native-get-random-values";
import { v4 } from "uuid";
export const getUUID = () => {
  return v4();
};
c 复制代码
import { getUUID } from "@/utils/UUID";
c 复制代码
    let id = getUUID();
    console.log("id", id);

本地存储

c 复制代码
npm i @react-native-async-storage/async-storage

utils/Storage.ts

c 复制代码
import AsyncStorage from "@react-native-async-storage/async-storage";
export const set = async (key: string, value: string) => {
  try {
    return await AsyncStorage.setItem(key, value);
  } catch (e) {
    console.log(e);
  }
};
export const get = async (key: string) => {
  try {
    return await AsyncStorage.getItem(key);
  } catch (e) {
    console.log(e);
  }
};
export const del = async (key: string) => {
  try {
    return await AsyncStorage.removeItem(key);
  } catch (e) {
    console.log(e);
  }
};

使用范例

c 复制代码
import { get, set } from "@/utils/Storage";
c 复制代码
  const save = () => {
    if (!id) {
      const newAccount = {
        id: getUUID(),
        type,
        platformName,
        account,
        password,
      };
      get("accountList").then((data) => {
        let accountList = data ? JSON.parse(data) : [];
        accountList.push(newAccount);
        set("accountList", JSON.stringify(accountList)).then(() => {
          hide();
        });
      });
    }
  };
相关推荐
朝阳397 小时前
ReactNative【实战系列教程】我的小红书 3 -- 自定义底栏Tab导航(含图片选择 expo-image-picker 的使用)
react native
冰冷的bin11 小时前
【React Native】自定义倒计时组件CountdownView
react native
朝阳3911 天前
React Native【实战范例】同步跟随滚动
react native
朝阳3912 天前
React Native【详解】动画
react native
朝阳3913 天前
React Native【详解】内置 API
react native
xx240613 天前
React Native学习笔记
笔记·学习·react native
朝阳3913 天前
React Native【实战范例】弹跳动画菜单导航
react native
草明14 天前
解决: React Native iOS webview 空白页
react native·react.js·ios
@PHARAOH14 天前
WHAT - React Native 开发 App 从 0 到上线全流程周期
javascript·react native·react.js