React Native Context 實現APP的主題開發

2020-10-04 11:00:14

重口難調,如果APP的主色調可以自定義,一定程度上就解決了這個問題。

實現思路 

  1. 每個元件之間共用同一個color變數,當使用者自定義主題顏色的時候,所有的頁面主色調一起發生變化。並且把使用者設定的顏色儲存到本地儲存之中。
  2. APP每次啟動的時候,從本地儲存中獲取主題的顏色資訊。

效果如下:

js/context/ThemeContext.js

/* eslint-disable prettier/prettier */
import React, {useState,useEffect, createContext} from 'react';
import AsyncStorage from '@react-native-community/async-storage';

export const ThemeContext = createContext();

export const ThemeProvider = props => {
    const [backgroundColor,setBackgroundColor] = useState('#1677ff');   //#1677ff
    useEffect(()=>{
        const queryThemeConfig = async () => {
            try {
                const cacheBackgroundColor = await AsyncStorage.getItem('@backgroundColor');
                if(cacheBackgroundColor!=null){
                    setBackgroundColor(cacheBackgroundColor);
                }
            } catch (e) {
                // saving error
            }
        };
        queryThemeConfig().then(r => void(0) );
    },[]);
    return (
        <ThemeContext.Provider value={[backgroundColor,setBackgroundColor]}>
            {props.children}
        </ThemeContext.Provider>
    );
};

js/screen/SettingsScreen.js

/* eslint-disable prettier/prettier */
import React, { useState,useContext } from "react";
import { FlatList, SafeAreaView, StatusBar, StyleSheet, Text, TouchableOpacity } from "react-native";
import {ThemeContext} from '../context/ThemeContext';
import AsyncStorage from '@react-native-community/async-storage';
const themeData = [
    {
        text: 'Default',
        color: '#1677ff',
    },
    {
        text: 'Red',
        color: '#F44336',
    },
    {
        text: 'Pink',
        color: '#E91E63',
    },
    {
        text: 'Purple',
        color: '#9C27B0',
    },
    {
        text: 'DeepPurple',
        color: '#673AB7',
    },
    {
        text: 'Indigo',
        color: '#3F51B5',
    },
    {
        text: 'Blue',
        color: '#2196F3',
    },
    {
        text: 'LightBlue',
        color: '#03A9F4',
    },
    {
        text: 'Cyan',
        color: '#00BCD4',
    },
    {
        text: 'Teal',
        color: '#009688',
    },
    {
        text: 'Green',
        color: '#4CAF50',
    },
    {
        text: 'LightGreen',
        color: '#8BC34A',
    },
    {
        text: 'Lime',
        color: '#CDDC39',
    },
    {
        text: 'Yellow',
        color: '#FFEB3B',
    },
    {
        text: 'Amber',
        color: '#FFC107',
    },
    {
        text: 'Orange',
        color: '#FF9800',
    },
    {
        text: 'DeepOrange',
        color: '#FF5722',
    },
    {
        text: 'Brown',
        color: '#795548',
    },
    {
        text: 'Grey',
        color: '#9E9E9E',
    },
    {
        text: 'BlueGrey',
        color: '#607D8B',
    },
    {
        text: 'Black',
        color: '#000000',
    }
];

const Item = ({ item, onPress, style }) => (
    <TouchableOpacity onPress={onPress} style={[styles.item, style]}>
        <Text style={styles.title}>{item.text}</Text>
    </TouchableOpacity>
);

const SettingScreen = () => {
    const [backgroundColor,setBackgroundColor] = useContext(ThemeContext);
    const saveThemeConfig = async (color) => {
        try {
            await AsyncStorage.setItem('@backgroundColor', color);
        } catch (e) {
            // saving error
        }
    };

    const renderItem = ({ item }) => {
        const backgroundColor = item.color;
        return (
            <Item
                item={item}
                onPress={() => {
                    setBackgroundColor(item.color);
                    saveThemeConfig(item.color);
                }}
                style={{ backgroundColor }}
            />
        );
    };

    return (
        <SafeAreaView style={styles.container}>
            <FlatList
                data={themeData}
                renderItem={renderItem}
                keyExtractor={(item) => item.text}
            />
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginTop: StatusBar.currentHeight || 0,
    },
    item: {
        padding: 20,
        marginVertical: 0,
        marginHorizontal: 0,
    },
    title: {
        fontSize: 22,
        color: '#ffffff',
    },
});

export default SettingScreen;

js/navigation/TabNav.js

/* eslint-disable prettier/prettier */
import React, {useContext} from 'react';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {createStackNavigator} from '@react-navigation/stack';
import SchoolScreen from '../screen/SchoolScreen';
import HomeScreen from '../screen/HomeScreen';
import MessageScreen from '../screen/MessageScreen';
import SettingsScreen from '../screen/SettingsScreen';
import AntDesign from 'react-native-vector-icons/AntDesign';
import {ThemeContext} from '../context/ThemeContext';

export default function Navigation({colorScheme}) {
    const [backgroundColor, setBackgroundColor] = useContext(ThemeContext);
    return (
        <Tab.Navigator
            screenOptions={({route}) => ({
                tabBarIcon: ({focused, color, size}) => {
                    if (route.name === 'index') {
                        return <AntDesign name="home" size={size} color={color}/>;
                    } else if (route.name === 'school') {
                        return <AntDesign name="cloudo" size={size} color={color}/>;
                    } else if (route.name === 'message') {
                        return <AntDesign name="mail" size={size} color={color}/>;
                    } else if (route.name === 'setting') {
                        return <AntDesign name="setting" size={size} color={color}/>;
                    }
                },
            })}
            tabBarOptions={{
                activeTintColor: backgroundColor,
            }}
        >
            <Tab.Screen
                name="index"
                component={HomeNavigator}
                options={{title: '首頁', headerMode: 'none'}}
            />
            <Tab.Screen
                name="school"
                component={SchoolNavigator}
                options={{title: '校園'}}
            />
            <Tab.Screen
                name="message"
                component={MessageNavigator}
                options={{title: '訊息'}}
            />

            <Tab.Screen
                name="setting"
                component={SettingsScreenNavigator}
                options={{title: '設定'}}
            />
        </Tab.Navigator>
    );
}
const Tab = createBottomTabNavigator();
const TabStack = createStackNavigator();

function HomeNavigator() {
    const [backgroundColor, setBackgroundColor] = useContext(ThemeContext);
    return (
        <TabStack.Navigator>
            <TabStack.Screen
                name="School"
                component={HomeScreen}
                options={{
                    headerTitle: '首頁',
                    headerLeft: null,
                    headerTitleAlign: 'center',
                    headerStyle: {
                        backgroundColor: backgroundColor,
                    },
                    headerTitleStyle:{
                        color: '#fff',
                    }
                }}
            />
        </TabStack.Navigator>
    );
}

function SchoolNavigator() {
    const [backgroundColor, setBackgroundColor] = useContext(ThemeContext);
    return (
        <TabStack.Navigator>
            <TabStack.Screen
                name="School"
                component={SchoolScreen}
                options={{
                    headerTitle: '校園',
                    headerLeft: null,
                    headerTitleAlign: 'center',
                    headerStyle: {
                        backgroundColor: backgroundColor,
                    },
                    headerTitleStyle:{
                        color: '#fff',
                    }
                }}
            />
        </TabStack.Navigator>
    );
}

function MessageNavigator() {
    const [backgroundColor, setBackgroundColor] = useContext(ThemeContext);
    return (
        <TabStack.Navigator>
            <TabStack.Screen
                name="School"
                component={MessageScreen}
                options={{
                    headerTitle: '訊息',
                    headerLeft: null,
                    headerTitleAlign: 'center',
                    headerStyle: {
                        backgroundColor: backgroundColor,
                    },
                    headerTitleStyle:{
                        color: '#fff',
                    }
                }}
            />
        </TabStack.Navigator>
    );
}

function SettingsScreenNavigator() {
    const [backgroundColor, setBackgroundColor] = useContext(ThemeContext);
    return (
        <TabStack.Navigator>
            <TabStack.Screen
                name="School"
                component={SettingsScreen}
                options={{
                    headerTitle: '主題設定',
                    headerLeft: null,
                    headerTitleAlign: 'center',
                    headerStyle: {
                        backgroundColor: backgroundColor,
                    },
                    headerTitleStyle:{
                        color: '#fff',
                    }
                }}
            />
        </TabStack.Navigator>
    );
}

App.js(入口檔案)

import React from 'react';
import {
  StyleSheet,
  SafeAreaView,
  StatusBar,
  useColorScheme,
} from 'react-native';
import Navigation from './js/navigation';
import {
  DarkTheme,
  DefaultTheme,
  NavigationContainer,
} from '@react-navigation/native';
import {ThemeProvider} from './js/context/ThemeContext';

const App = () => {
  const colorScheme = useColorScheme();
  return (
    <ThemeProvider>
      <NavigationContainer
        theme={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
        <Navigation />
        <StatusBar barStyle={'light-content'} />
      </NavigationContainer>
    </ThemeProvider>
  );
};

export default App;

專案原始碼下載:

https://download.csdn.net/download/lxyoucan/12910406