background
Because the company is a work software, it needs to be adapted to bright and dark themes.
Not recommended
The company used to be this kind of solution, which was time-consuming and labor-intensive.
It's in the root directory of the projectpublic
Create a folderFile, all dark styles in this file.
How to switch topics:
const getTheme = (isDark: boolean) => { const darkStyle: any = ('darkTheme'); if (!darkStyle) { var link = ('link'); = 'stylesheet'; = 'text/css'; = "darkTheme" = false; = './'; ('head')[0].appendChild(link); } = !!isDark; }
Recommended plan
By controllingcss
Variables to show two topics, which are convenient and concise.
Because the company uses itless
, so the followingless
As an example, butscss
andcss
It's the same.
1. Create two topics file
Create the theme folder under the src folder, and create it under this folderand
document.
:root[data-theme="light"] { --primary-text-color: #FFFFFF; --primary-white-color: #2A2A2D; --primary-color: #3591F4; --text-color: #363A45; }
:root[data-theme="light"] { --primary-text-color: #FFFFFF; --primary-white-color: #2A2A2D; --primary-color: #3591F4; --text-color: #fff; }
2. Introduce these two files at the entrance
@import './theme/'; @import './theme/';
3. In the tsx file at the entrance, in the method of the theme that can be obtained, call the method of switching the theme
const getDarkTheme = (isDark: boolean) => { const root = ; if (!isDark) { // Modify the value of the data-theme attribute to "light" ('data-theme', 'light'); return } // Modify the value of the data-theme attribute to "dark" ('data-theme', 'dark'); } getDarkTheme(theme)
Use Example
.btn { color: var(--primary-color); }
Summarize
In the react project, this method of modifying the css variables can dynamically modify the theme color. It is more convenient and concise. You only need to write only one css variable in actual use. Make the project style files better maintained.
The above is the detailed content of the React project's dynamic modification of theme colors. For more information about React's theme colors, please follow my other related articles!