nextjs color mode
1.0.0
建立不閃爍且可存取的主題應用程式的助手
prefers-color-scheme ) $ npm i --save nextjs-color-mode
# or
$ yarn add nextjs-color-mode
首先,您需要從nextjs-color-mode匯入ColorModeScript並將其放置在_app.js檔案中的某個位置。
如果您使用樣式元件或情感,則可以將
criticalThemeCss的內容放入 GlobalStyles 中。只要確保它是關鍵的 css,並且位於全局樣式的頂部即可。
// _app.js
import Head from 'next/head'
import { ColorModeScript } from 'nextjs-color-mode'
const criticalThemeCss = `
.next-light-theme {
--background: #fff;
--text: #000;
}
.next-dark-theme {
--background: #000;
--text: #fff;
}
body {
background: var(--background);
color: var(--text);
}
`
function MyApp ( { Component , pageProps } ) {
return (
< >
< Head >
< style dangerouslySetInnerHTML = { { __html : criticalThemeCss } } />
</ Head >
< ColorModeScript />
< Component { ... pageProps } />
</ >
)
} useColorSwitcher )要實作主題切換器,您應該使用useColorSwitcher鉤子
請注意,明確使用此掛鉤的每個元件都應僅在客戶端呈現。在範例中查看我們如何執行此操作
import { ColorModeStyles , useColorModeValue , useColorSwitcher } from 'nextjs-color-mode'
export default function ColorSwitcher ( props ) {
const { toggleTheme , colorMode } = useColorSwitcher ( )
return (
< button onClick = { toggleTheme } >
Change theme to { colorMode === 'light' ? 'dark' : 'light' }
</ button >
)
} function useColorSwitcher ( ) : {
colorMode : string ;
changeTheme : ( colorMode : 'light' | 'dark' ) => void ;
toggleTheme : ( ) => void ;
} ; useColorModeValue )有時您可能會想要省略設計系統或需要快速修復某些內容。這是解決方案。
export default function SomeComponent ( ) {
const [ boxBgColor , boxBgCss ] = useColorModeValue ( 'box-color' , 'blue' , 'red' )
const [ boxBorderColor , boxBorderCss ] = useColorModeValue ( 'box-border-color' , 'red' , 'blue' )
// the first item of the array returns CSS variable name
// and the second one returns a special object that then gets parsed into a themable CSS variable
return (
< >
< ColorModeStyles styles = { [ boxBgCss , boxBorderCss ] } />
< div style = { { width : '24rem' , height : '12rem' , backgroundColor : boxBgColor , border : "10px solid" , borderColor : boxBorderColor } } />
</ >
)
} function useColorModeValue ( name : string , lightThemeValue : string , darkThemeValue : string ) ;不要使用相同的名稱兩次,這可能會導致變數覆蓋並且難以調試。另外,使用諸如唯一 id、UUID 或任何隨機生成的字元集之類的東西都是一個壞主意 - 它會顯示不匹配內容警告,並使調試變得更加困難!
如果您正在尋求幫助或只是想分享您對這個專案的想法,我們鼓勵您加入我們的 Discord 社群。連結如下:https://blazity.com/discord。這是一個我們交流想法、互相幫助的空間。感謝大家的意見,我們期待您的光臨。