ホームページ >ウェブフロントエンド >CSSチュートリアル >反応のイージーダークモード(および複数の色のテーマ!)
このガイドは、使用の使いやすさとチームのオンボーディングに焦点を当てた、Reactアプリケーションでの簡単なダークモードの実装を示しています。複雑なCSS戦略を回避し、クリーンで効率的なソリューションのCSS変数とデータ属性を活用します。
スタイルを管理し、大規模なReactプロジェクトでダークモードを実装するという課題は、しばしば複雑なソリューションにつながります。多くのオプションが存在しますが、特定のCSS方法論またはフレームワークに頻繁に依存しています。このアプローチは、シンプルさと速度を優先し、スキルレベルのさまざまなチームに最適です。
An improved method, combining CSS variables with the useLocalStorage
hook, provides a robust and user-friendly theming system.このチュートリアルでは、このシステムをゼロからセットアップして実行し、新しいReactアプリでその有効性を紹介します。 Furthermore, it demonstrates integration with react-scoped-css
for enhanced CSS organization.
このガイドは、CSS、JavaScript、およびReactに基本的な精通度を想定しています。ノードとNPMがインストールされていることを確認してください。以下を使用して新しいReactアプリを作成します。
NPX Create-React-App Easy-React-Themes - Template TypeScript
(Replace easy-react-themes
with your project name; omit --template typescript
for JavaScript). Open the project in your code editor (eg, VS Code using cd easy-react-themes; code .
) and start the development server ( npm start
). Finally, install use-local-storage
:
npm i use-local-storage
Clear the contents of App.css
. In index.css
, define your themes using CSS variables:
:根 { - バックグラウンド:白; - テキストプリマリー:ブラック; - テキストセコンダリー:RoyalBlue; - アクセント:紫。 } [data-theme = 'dark'] { - バックグラウンド:黒; - テキストプリマリー:白。 - テキストセコンダリー:灰色; - アクセント:darkred; }
これは、CSSカスタムプロパティ(変数)とデータ属性を利用します。 The [data-theme='dark']
selector overrides the :root
variables when the data-theme
attribute is set to 'dark'.
In App.tsx
, import useLocalStorage
:
「use-local-storage」からuselocalStorageをインポートします。
次に、テーマ状態を管理します。
const defaultdark = window.matchmedia( '(color-scheme:dark)')。マッチ; const [theme、settheme] = uselocalStorage( 'theme'、defaultdark? 'dark': 'light');
This uses useLocalStorage
to persist theme selection across sessions, respecting browser preferences. The data-theme
attribute is applied to the top-level<div> :<pre class="brush:php;toolbar:false"><div data-theme="{theme}">
{/ *ここのアプリコンテンツ */}
</div></pre>
<p>Style your components in <code>App.css
using the CSS variables:
。アプリ { 色:var( - テキストプリマリー); バックグラウンドカラー:var( - background); / * ...その他のスタイル... */ 遷移:すべて.5; } ボタン { / * ... CSS変数を使用したボタンスタイル... */ 遷移:すべて.5; }
これにより、テーマが変更されるとスタイルがスムーズに更新されます。テーマを切り替えるボタンを追加します。
新しいコンポーネント(たとえば、色付きの正方形)を追加して、システムのスケーラビリティを示します。 Import this component into App.tsx
.
For improved CSS organization, integrate react-scoped-css
. Follow the installation instructions for CRACO and craco-plugin-scoped-css
. Rename your CSS files (eg, app.css
to app.scoped.css
) and update imports accordingly. Crucially, leave index.css
unscoped to ensure global application of CSS variables.
このアプローチは、ダークモードと複数のテーマをReactアプリケーションに実装するためのシンプルで効果的で保守可能なソリューションを提供します。 GitHubリポジトリとライブデモは、さらなるリソースを提供します。
以上が反応のイージーダークモード(および複数の色のテーマ!)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。