当前位置: 首页 > 后端技术 > Node.js

搭建个人知识付费应用系统-(四)Remixi18n、主题切换

时间:2023-04-04 01:23:52 Node.js

瑙嗛鍦板潃锛歨ttps://www.bilibili.com/video...Remixi18n娉ㄦ剰languages鐨勭粨鏋勮皟鏁达細exportconstlanguages={zh:{flag:'馃嚚馃嚦',name:'绠€浣撲腑鏂?},en:{flag:'馃嚭馃嚫',name:'English'}};璇█鍒囨崲缁勪欢鍚孌aisyUIimport{useI18n}from'remix-i18n';浠?鍙嶅簲'瀵煎叆{useEffect锛寀seState}锛沬mport{useLocation}from'@remix-run/react';import{getLocale,languages}from'~/i18n';exportfunctionToggleLocale(){const{t}=useI18n();constlocation=useLocation();const[path,setPath]=useState(location.pathname.replace(`/${getLocale(location.pathname)}`,''));useEffect(()=>{setPath(location.pathname.replace(`/${getLocale(location.pathname)}`,''));},[location]);杩斿洖(

{Object.entries(languages).map(([locale,item])=>({item.flag}{item.name}))}
);}Remix涓婚鍒囨崲鍒囨崲涓婚鎺ュ彛/api/themeimport{typeLoaderFunction,redirect,typeActionFunction,json}from'@remix-杩愯/鑺傜偣'锛涗粠'~/components/atom/use-theme'瀵煎叆{涓婚}锛涗粠'~/services/session.server'瀵煎叆{getSession}锛涘鍑哄父閲忔搷浣滐細ActionFunction=寮傛锛坽璇锋眰}锛?>{寮€鍏砲(request.method){case'PUT':case'POST':{constsession=awaitgetSession(request.headers.get('Cookie'));constdata:{theme:string}=awaitrequest.json();consttheme=themes.map((x)=>x.id).includes(data.theme)锛焏ata.theme:'澶嶅彜';session.set('涓婚',涓婚);returnjson({success:true},{headers:{'Set-Cookie':awaitsessionStore.commitSession(session)}});}榛樿鍊硷細{returnjson({success:false},{status:403});}}};exportconstloader:LoaderFunction=()=>{throwredirect('/');};ThemeProviderimport{createContext}from'react';exportconstthemes=[{name:'馃対銆噇ight',id:'light'},{name:'馃寶dark',id:'dark'},{name:'馃cupcake',id:'cupcake'},{name:'馃悵bumblebee',id:'bumblebee'},{name锛?鉁筹笍Emerald'锛宨d锛?emerald'}锛寋name锛?馃彚Corporate'锛宨d锛?corporate'}锛寋name锛?馃寖synthwave'锛宨d锛?synthwave'}锛寋name锛?馃懘retro',id:'retro'},{name:'馃銆嘽yberpunk',id:'cyberpunk'},{name:'馃尭銆噕alentine',id:'valentine'},{name:'馃巸銆噃alloween',id:'涓囧湥鑺?},{name:'馃尫garden',id:'鑺卞洯'},{name:'馃尣forest',id:'forest'},{name:'馃悷aqua',id:'aqua'},{name:'馃憮銆噇ofi',id:'lofi'},{name:'馃枍銆噋astel',id:'pastel'},{name:'馃鈥嶏笍銆噁antasy',id:'fantasy'},{name:'馃摑Wireframe',id:'wireframe'},{name:'馃彺black',id:'black'},{name:'馃拵luxury',id:'luxury'},{name:'馃鈥嶁檪锔廳racula',id:'寰峰彜鎷?},{name:'馃枿銆嘋MYK',id:'cmyk'},{name:'馃崄銆嘇utumn',id:'绉嬪ぉ'},{name:'馃捈銆嘊usiness',id:'business'},{鍚嶇О:'馃拪銆囬吀',鎴慸:'acid'},{name:'馃崑銆嘗emonade',id:'lemonade'},{name:'馃寵銆嘚ight',id:'night'},{name:'鈽曪笍銆嘋offee',id:'鍜栧暋'},{name:'鉂勶笍銆嘩inter',id:'winter'}];typeThemeContextType=[string|绌猴紝React.Dispatch>];constThemeContext=createContext(undefined);ThemeContext.displayName='ThemeContext';constprefersLightMQ='(prefers-color-scheme:light)';瀵煎嚭鍑芥暟ThemeProvider({children,themeAction='/api/theme',specifiedTheme}:{children:ReactNode;themeAction:string;specifiedTheme:string|null;}){const[theme,setTheme]=useState(()=>{if(specifiedTheme){returnTHEMES.includes(specifiedTheme)?specifiedTheme:null;}if(typeofwindow!=='object')returnnull;returnwindow.matchMedia(prefersLightMQ).matches锛熲€滄儏浜鸿妭鈥濓細鈥滃鍙も€濓紱}锛夛紱甯告暟mountRun=React.useRef(false);useEffect(()=>{if(!mountRun.current){mountRun.current=true;return;}if(!theme)return;//eslint-disable-next-line@typescript-eslint/no-floating-promisesfetch(`${themeAction}`,{method:'POST',body:JSON.stringify({theme})});},[theme]);useEffect(()=>{constmediaQuery=window.matchMedia(prefersLightMQ);consthandleChange=()=>{setTheme(mediaQuery.matches?'valentine':'retro');};mediaQuery.addEventListener('change',handleChange);return()=>mediaQuery.removeEventListener('change',handleChange);},[]);return({children});}瀵煎嚭鍑芥暟useTheme(){constcontext=useContext(ThemeContext);if(context===undefined){thrownewError('useTheme蹇呴』鍦═hemeProvider涓娇鐢?);}杩斿洖缁璭xt;}浣跨敤Themeexportconstloader:LoaderFunction=async({request})=>{constsession=awaitgetSession(request.headers.get('Cookie'));consttheme=(session.get('theme')asstring)||'澶嶅彜鐨?;returnjson({theme});};瀵煎嚭榛樿鍑芥暟App(){const{theme}=useLoaderData();return();}鍒囨崲涓婚缁刬mport{useI18n}from'remix-i18n';import{themes}from'./use-theme';exportfunctionToggleTheme(){const{t}=useI18n();杩斿洖({/*{$t('change-theme-btn')}*/}
{themes.map((theme)=>({theme.id}))});}缁勪欢娣诲姞鍒囨崲浜嬩欢const[currentTheme,setTheme]=useTheme();constonThemeClicked=(theme:string)=>{setTheme(theme);//eslint-disable-next-line@typescript-eslint/no-floating-promisesfetch('/api/theme',{method:'PUT',body:JSON.stringify({theme})});localStorage.setItem('涓婚',涓婚);};

最新推荐
猜你喜欢