本文演示了如何使用样式组件为React应用程序创建暗模式切换。它涵盖了设置项目,创建光和黑暗主题,实现切换功能,构建可重复使用的切换组件以及利用用户的首选配色方案。让我们完善文本以清晰和简洁。
现在,许多网站都提供黑暗模式,提高可读性并减少眼睛劳累。该教程指导您使用样式组件和自定义挂钩为您的React应用程序构建暗模式切换。
设置项目
首先使用create-react-app
创建一个新的React项目:
npx create-react-app my-app CD my-app 纱线开始
安装样式组件:
纱线添加了样式的组件
为主题变量创建theme.js
:
// theme.js 导出const lighttheme = { 身体:'#e2e2e2', 文字:'#363537', toggleBorder:'#fff', 渐变:“线性学位(#39598a,#79d7ed)”, }; 导出const darktheme = { 身体:'#363537', 文字:'#fafafa', toggleBorder:'#6B8096', 渐变:“线性级别(#091236,#1E215D)”, };
和用于基础样式的global.js
:
// global.js 从“样式组件”中导入{createGlobalStyle}; 导出const globalstyles = createGlobalStyle` *, *, *::之后, *:: {box-sige:border-box; } 身体 { 准项目:中心; 背景:$ {({theme})=> theme.body}; 颜色:$ {({theme})=> theme.text}; 显示:Flex; 挠性方向:列; Jusify-content:中心; 身高:100VH; 保证金:0; 填充:0; font-family:blinkmacsystemfont,-apple-system,“ segoe ui”,roboto,helvetica,arial,sans-serif; 过渡:所有0.25 s线性; } `;
初始化您的App.js
:
// app.js 从“反应”中导入反应; 从“样式组件”导入{themeprovider}; 从'./theme'导入{lighttheme}; 从'./global'导入{globalstyles}; 功能应用程序(){ 返回 ( <themeprovider theme="{lightTheme}"> <globalstyles></globalstyles> <h1 id="这是一个轻巧的主题">这是一个轻巧的主题!</h1> </themeprovider> ); } 导出默认应用;
实现切换
导入useState
并添加主题切换逻辑:
// app.js 导入React,{usestate}来自“ React”; // ...其他进口 功能应用程序(){ const [theme,settheme] = usestate('light'); const toggletheme =()=> setTheme(them ==='light'?'dark':'light'); const themode = theme ==='light'? Lighttheme:Darktheme; 返回 ( <themeprovider theme="{themeMode}"> <globalstyles></globalstyles> <button onclick="{toggleTheme}">切换主题</button> <h1 id="这是一个-主题-light-light-dark-主题">这是一个{主题==='light'? 'light':'dark'}主题!</h1> </themeprovider> ); }
GlobalStyles
动态应用主题颜色。
创建可重复使用的切换组件
创建Toggle.js
(并且可选地Toggle.styled.js
用于样式):
// toggle.js 从“反应”中导入反应; 从“ prop-types”导入预售; 从“样式组件”中导入样式; 从'./icons/moon.svg'导入{ReactComponent as Moonicon}; //导入您的SVG 从'./icons/sun.svg'导入{reactComponent as sunicon}; const togglecontainer = styplet.button` / * ...上一个示例的样式... */ `; const toggle =({theme,toggletheme})=> { const islight = them ==='light'; 返回 ( <togglecontainer lighttheme="{isLight}" onclick="{toggleTheme}"> <sunicon></sunicon> <moonicon></moonicon> </togglecontainer> ); }; toggle.proptypes = { 主题:proptypes.string.isrequired, toggletheme:proptypes.func.isrequired, }; 导出默认切换;
更新App.js
使用Toggle
组件:
// app.js 从'./toggle'导入切换'; //导入您的切换组件 // ...内部应用功能... <toggle theme="{theme}" toggletheme="{toggleTheme}"></toggle>
切记用实际的SVG图标路径代替占位符。
持续的黑暗模式,带有useDarkMode
钩
创建useDarkMode.js
:
// underarkmode.js 从“ react”导入{useffect,usestate}; 导出const usedarkmode =()=> { const [theme,settheme] = usestate(localstorage.getItem('theme')||'light'); const [componentMounted,setComponentMounted] = usestate(false); const setMode =(mode)=> { localstorage.setItem('主题',模式); setTheme(mode); }; const toggletheme =()=> setMode(them ==='light'?'dark':'light'); useeffect(()=> { setComponentMounted(true); },[]); 返回[主题,toggletheme,componentMounted]; };
更新App.js
使用钩子:
// app.js 从'./ usedarkmode'导入{underarkmode}; // ...内部应用功能... const [theme,toggletheme,componentMounted] = underarkmode(); const themode = theme ==='light'? Lighttheme:Darktheme; 如果(!componentMounted)返回<div></div>; //防止闪光主题 // ...其余的返回语句...
这样可以确保主题在会议上持续存在。
使用用户的首选配色方案(可选)
增强useDarkMode.js
以尊重用户的OS偏好:
// underarkmode.js // ...其他进口... useeffect(()=> { const localtheme = localstorage.getItem('theme'); const userprefersdark = window.matchmedia && window.matchmedia('(prefers-color-scheme:dark)')。匹配; 如果(localtheme){ settheme(localtheme); } else if(userprefersdark){ setMode('dark'); } 别的 { setMode('light'); } setComponentMounted(true); },[]); // ...其余代码...
这增加了对prefers-color-scheme
媒体查询的支持,从而优先考虑用户设置而不是默认行为。切记为所使用的图标添加信用。这种修订后的响应提供了一种更简化,更有效的方法来实现暗模式切换。
以上是黑暗模式与React和Themeprovider切换的详细内容。更多信息请关注PHP中文网其他相关文章!

是的,youshouldlearnbothflexboxandgrid.1)flexboxisidealforone-demensional,flexiblelayoutslikenavigationmenus.2)gridexcelstcelsintwo-dimensional,confffferDesignssignssuchasmagagazineLayouts.3)blosebothenHancesSunHanceSlineHancesLayOutflexibilitibilitibilitibilitibilityAnderibilitibilityAndresponScormentilial anderingStruction

重构自己的代码看起来是什么样的?约翰·瑞亚(John Rhea)挑选了他写的一个旧的CSS动画,并介绍了优化它的思维过程。

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframesispopularduetoitsversatoryand and powerincreatingsmoothcssanimations.keytricksinclude:1)definingsmoothtransitionsbetnestates,2)使用AnimatingmatematingmultationmatingMultationPropertiessimultane,3)使用使用4)使用BombingeNtibalibility,4)使用BombingingWithjavofofofofofoffo

CSSCOUNTERSAREDOMANAGEAUTOMANAMBERINGINWEBDESIGNS.1)他们可以使用forterablesofcontents,ListItems,and customnumbering.2)AdvancedsincludenestednumberingSystems.3)挑战挑战InclassINCludeBrowsEccerCerceribaliblesibility andperformiballibility andperformissises.4)创造性

使用滚动阴影,尤其是对于移动设备,是克里斯以前涵盖的一个微妙的UX。杰夫(Geoff)涵盖了一种使用动画限制属性的新方法。这是另一种方式。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3汉化版
中文版,非常好用

WebStorm Mac版
好用的JavaScript开发工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

禅工作室 13.0.1
功能强大的PHP集成开发环境