美文网首页
RN 切换主题

RN 切换主题

作者: 精神病患者link常 | 来源:发表于2022-06-13 00:54 被阅读0次

    方式一:https://www.jianshu.com/p/8ce1ef5dfc59
    方式二:切换主题就是切换style,通过reduce的修改切换

    思路:
    1.创建themeReduce,保存 light/dark
    2.创建style时,获取themeReduce的值,通过colors配置读取对应的数据

    1.创建主题reduce、colors

    import { createSlice, PayloadAction } from "@reduxjs/toolkit";
    const initialState:any = {
      theme:'light',
    }
    
    // light dark
    type ThemeParams = {
      themeName:string,
    }
    
    export const Theme = createSlice({
      name:'theme',
      initialState:initialState,
      reducers:{
        changeTheme:(state:any,actions:PayloadAction<ThemeParams>)=>{
          state.theme = actions.payload.themeName
        }
      }
    })
    
    export const {changeTheme} = Theme.actions
    export default Theme.reducer
    
    
    const Colors:any = {
      light: {
        text: '#000',
        background: '#fff',
      },
      dark: {
        text: '#fff',
        background: '#000',
      },
    };
    

    2.创建hook

    export default function useColorScheme() {
      const themeName = useSelector((state:any) => state.theme.theme)
      return themeName
    }
    

    3.创建style

    import { StyleSheet } from 'react-native'
    import { Platform } from 'react-native'
    import Colors from '../../constants/Colors'
    import useColorScheme from '../../hooks/useColorScheme'
    
    const dynamicStyles = () => {
      const theme = useColorScheme()
      const colorTheme = Colors[theme]
      return StyleSheet.create({
        mainView:{
          flex: 1,
          backgroundColor: colorTheme.background,
        },
      })
    }
    export default dynamicStyles
    

    4.页面使用

    const styles = dynamicStyles()
    
    function onChangeTheme(){
      dispatch(changeTheme({themeName:'dark'}))
    }
    
    <TouchableOpacity style={styles.btnsetting} onPress={onChangeTheme}>
      <Text>切换主题</Text>
    </TouchableOpacity>
    

    相关文章

      网友评论

          本文标题:RN 切换主题

          本文链接:https://www.haomeiwen.com/subject/wwgnmrtx.html