搜尋
首頁web前端css教學黑暗模式與React和Themeprovider切換

本文演示瞭如何使用樣式組件為React應用程序創建暗模式切換。它涵蓋設置項目,創建淺色和深色主題,實現切換功能,構建可重複使用的切換組件以及利用用戶的首選配色方案。讓我們完善文本以清晰和簡潔。

黑暗模式與React和Themeprovider切換

現在,許多網站都提供黑暗模式,提高可讀性並減少眼睛勞累。該教程指導您使用樣式組件和自定義掛鉤為您的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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
CSS動畫:很難創建它們嗎?CSS動畫:很難創建它們嗎?May 09, 2025 am 12:03 AM

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

@KeyFrames CSS:最常用的技巧@KeyFrames CSS:最常用的技巧May 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatoryand and powerincreatingsmoothcsssanimations.keytricksinclude:1)definingsmoothtransitionsbetnestates,2)使用AnimatingMultatingMultationMultationProperPertiessimultane,3)使用使用4)使用BombingeNtibalibility,4)使用CombanningWiThjavoFofofofoftofofo

CSS計數器:自動編號的綜合指南CSS計數器:自動編號的綜合指南May 07, 2025 pm 03:45 PM

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

使用捲軸驅動動畫的現代滾動陰影使用捲軸驅動動畫的現代滾動陰影May 07, 2025 am 10:34 AM

使用滾動陰影,尤其是對於移動設備,是克里斯以前涵蓋的一個微妙的UX。傑夫(Geoff)涵蓋了一種使用動畫限制屬性的新方法。這是另一種方式。

重新訪問圖像圖重新訪問圖像圖May 07, 2025 am 09:40 AM

讓我們快速進修。圖像地圖一直返回到HTML 3.2,首先是服務器端地圖,然後使用映射和區域元素通過圖像上的單擊區域定義了可單擊區域。

DEV狀態:每個開發人員的調查DEV狀態:每個開發人員的調查May 07, 2025 am 09:30 AM

開發委員會調查現已開始參與,並且與以前的調查不同,它涵蓋了除法:職業,工作場所,以及健康,愛好等。 

什麼是CSS網格?什麼是CSS網格?Apr 30, 2025 pm 03:21 PM

CSS網格是創建複雜,響應式Web佈局的強大工具。它簡化了設計,提高可訪問性並提供了比舊方法更多的控制權。

什麼是CSS Flexbox?什麼是CSS Flexbox?Apr 30, 2025 pm 03:20 PM

文章討論了CSS FlexBox,這是一種佈局方法,用於有效地對齊和分佈響應設計中的空間。它說明了FlexBox用法,將其與CSS網格進行了比較,並詳細瀏覽了瀏覽器支持。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。