NativeBase 的使用
1.安装
bash
yarn add native-base react-native-svg@12.1.1 react-native-safe-area-context@3.3.2
2.设置
NativeBaseProvider 是一个组件,可使主题在整个应用中可用。它使用 React 的 Context API。将 NativeBaseProvider 添加到应用的根目录并更新 App.js 如下所示:
app.js
jsx
import React from "react";
// 1. import `NativeBaseProvider` component
import { NativeBaseProvider, Text, Box } from "native-base";
export default function App() {
// 2. Use at the root of your app
return (
<NativeBaseProvider>
<Box flex={1} bg='#fff' alignItems='center' justifyContent='center'>
<Text>Open up App.js to start working on your app!</Text>
</Box>
</NativeBaseProvider>
);
}
3.添加自定义主题
如果您需要自定义默认主题以匹配您的设计要求,您可以从 native-base 扩展主题。
NativeBase 3.0 提供了一个 extendTheme 函数,该函数将默认主题与您的自定义项深度合并。
jsx
// 1. Import the extendTheme function
import { extendTheme, NativeBaseProvider } from "native-base";
// 2. Extend the theme to include custom colors, fonts, etc
const newColorTheme = {
primary: {
50: "#6fc6f3",
100: "#5dbff2",
200: "#4bb8f0",
300: "#39b0ef",
400: "#27a9ed",
500: "#15a2ec",
600: "#1296db",
700: "#118ac9",
800: "#0f7db7",
900: "#0e71a5",
},
brand: {
900: "#8287af",
800: "#7c83db",
700: "#b3bef6",
},
};
const theme = extendTheme({ colors: newColorTheme });
// 3. Pass the `theme` prop to the `NativeBaseProvider`
function App() {
return (
<NativeBaseProvider theme={theme}>
<App />
</NativeBaseProvider>
);
}
主题色说明
600 是主题色,其它值表示该主题色的深度值
获取其它的深度值,可以访问https://www.colorhexa.com/index.php
4.暗黑主题切换
如果你想对你的应用中的颜色模式做一些事情,你可以使用 NativeBaseProvider 的 colorModeManager Prop 来实现它。
在下面的示例中,我们将演示如何将活动的 ColorMode 存储在异步存储中,以便它可以在应用周围保持一致。
jsx
import React from "react";
import { NativeBaseProvider, ColorMode } from "native-base";
import type { StorageManager } from "native-base";
import AsyncStorage from "@react-native-async-storage/async-storage";
export default ({ children, theme }: any) => {
const colorModeManager: StorageManager = {
get: async () => {
try {
let val = await AsyncStorage.getItem("@my-app-color-mode");
return val === "dark" ? "dark" : "light";
} catch (e) {
console.log(e);
return "light";
}
},
set: async (value: ColorMode) => {
try {
await AsyncStorage.setItem("@my-app-color-mode", value);
} catch (e) {
console.log(e);
}
},
};
return (
<NativeBaseProvider theme={theme} colorModeManager={colorModeManager}>
{/* Your App Goes Here */}
</NativeBaseProvider>
);
};
5.默认主题颜色值
primary
primary.50
#ecfeff
primary.100
#cffafe
primary.200
#a5f3fc
primary.300
#67e8f9
primary.400
#22d3ee
primary.500
#06b6d4
primary.600
#0891b2
primary.700
#0e7490
primary.800
#155e75
primary.900
#164e63