React Native【实用教程】(含图标方案,常用第三库,动画,内置组件,内置Hooks,内置API,自定义组件,创建项目等)
搭建开发环境,创建启动项目
https://blog.csdn.net/weixin_41192489/article/details/147728955
样式
-
默认的 font-size 是 14
-
安卓中 font-weight 只支持 normal 和 bold ,而 IOS 中都支持
-
padding 的定义方式
<View style={{ paddingTop: 10, paddingBottom: 10, paddingLeft: 20, paddingRight: 20 }}>{/* 内容 */} </View>// 或使用简写属性 <View style={{ paddingHorizontal: 20, paddingVertical: 10 }}>{/* 内容 */} </View>
注意事项
-
不支持百分比布局(应用 flex 布局)
-
绝对单位需省略(不能写 px ,rem 等绝对单位)
<View style={{ width: 100, height: 50 }} /> // 相当于 width: 100dp (Android) 或 width: 100pt (iOS)
内联样式
<Text style={{color: 'red',fontWeight: 'bold'}}>标题</Text>
【推荐】样式表
样式表比内联样式性能更高
- 通过 StyleSheet.create 创建
- 在组件上,给 style 属性赋值,支持数组的形式添加多个
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
const styles = StyleSheet.create({box: {width: 100,height: 100,backgroundColor: 'blue',transformStyle: 'preserve-3d', // 保持 3D 变换transform: [{ rotate: '45deg' }, // 旋转{ scale: 1.5 }, // 缩放],},
});
{ rotate: '45deg' } // 顺时针旋转 45 度
{ rotateX: '45deg' } // 绕 X 轴旋转(3D 效果)
{ rotateY: '45deg' } // 绕 Y 轴旋转(3D 效果)
{ rotateZ: '45deg' } // 绕 Z 轴旋转(等同于 rotate)
{ scale: 1.5 } // 等比放大 1.5 倍
{ scaleX: 2 } // 水平方向放大 2 倍
{ scaleY: 0.5 } // 垂直方向缩小 50%
{ translateX: 50 } // 向右平移 50 像素
{ translateY: -50 } // 向上平移 50 像素
{ translateZ: 100 } // 向 Z 轴平移(3D 效果)
{ skewX: '30deg' } // 水平倾斜 30 度
{ skewY: '30deg' } // 垂直倾斜 30 度
图标
Expo 的 React Native 项目中内置了@expo/vector-icons,可直接使用
搜索图标: https://icons.expo.fyi/Index
复制到项目中使用即可,如
import Entypo from '@expo/vector-icons/Entypo';
<Entypo name="home" size={24} color="black" />
内置组件
https://blog.csdn.net/weixin_41192489/article/details/148612134
获取元素最终渲染的宽高和位置信息
使用 onLayout (仅内置组件可用)
<Viewstyle={{ 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
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>);
}
导入使用
import { UserInfoView } from "@/components/userInfo";
<UserInfoView name="朝阳" level={1} />
支持直接传 JSX
见 moreInfo
const moreInfo = () => {return <Text>兴趣爱好:编程</Text>;};return <UserInfoView name="朝阳" level={1} moreInfo={moreInfo()} />;
export function UserInfoView({name,level,moreInfo,
}: {name: string;level: number;moreInfo?: React.ReactNode;
}) {return (<Text>用户名:{name}{levelView(level)}{moreInfo}</Text>);
}
子元素作为 children 传递
见 “可以”
<UserInfoView>可以</UserInfoView>
components/userInfo.tsx
import React from "react";
import { Text } from "react-native";
export function UserInfoView({ children }: { children?: React.ReactNode }) {return <Text>{children}</Text>;
}
内置 Hooks
获取页面元素 useRef
import { useRef } from "react";
import { View } from "react-native";
export default function HomeScreen() {const viewRef = useRef(null);console.log(viewRef.current);return (<><Viewref={viewRef}style={{ width: 100, height: 200, backgroundColor: "red" }}></View></>);
}
其中 viewRef.current 中常用的属性和方法为:
- measure : 一个方法,用于获取视图相对于父视图的位置和尺寸。
- measureInWindow : 一个方法,用于获取视图相对于窗口的位置和尺寸。
- measureLayout : 一个方法,用于获取视图相对于另一个视图的位置和尺寸。
- focus : 一个方法,用于将焦点设置到视图上(如果视图支持焦点)。
- blur : 一个方法,用于移除视图上的焦点(如果视图支持焦点)。
获取屏幕信息 useWindowDimensions
- width:number 类型,代表相应尺寸的宽度,单位是与设备像素无关的逻辑像素点。
- height:number 类型,代表相应尺寸的高度,单位是与设备像素无关的逻辑像素点。
- scale:number 类型,是设备的像素密度,即物理像素与逻辑像素的比例。
- fontScale:number 类型,是设备的字体缩放比例因子,用于调整字体大小。
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
import { Text, useColorScheme } from "react-native";
export default function HomeScreen() {const colorScheme = useColorScheme();return (<><Text>{colorScheme}</Text></>);
}
在手机设置中进行切换后,值变成 dark
支持的事件
点击和长按
<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
在性能瓶颈/需要页面立马更新时使用,用得少
const viewRef = useRef<View>(null);if (viewRef.current) {viewRef.current.setNativeProps({style: {backgroundColor: "blue",},});}
常用第三方库
生成唯一 id
npm i react-native-get-random-values
npm i uuid
使用
utils/UUID.ts
import "react-native-get-random-values";
import { v4 } from "uuid";
export const getUUID = () => {return v4();
};
import { getUUID } from "@/utils/UUID";
let id = getUUID();console.log("id", id);
本地存储
npm i @react-native-async-storage/async-storage
utils/Storage.ts
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);}
};
使用范例
import { get, set } from "@/utils/Storage";
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();});});}};