antd 黑暗模式 (v5 react)
不知道为啥 🤷 官网根本没写怎么切换
1. 开启这个东西,是用configprovide
import { ConfigProvider, theme } from 'antd';<ConfigProvidertheme={{algorithm: isDark ? theme.darkAlgorithm : theme.defaultAlgorithm,}}>
2. 然后一些默认的,会自己定义好,没定义的,就需要自己写
观察切换后,模式有了什么改变
好吧,它没改变,这个东西难道要自己写。。,,
// 正确初始化状态(建议使用布尔值)const [isDark, setIsDark] = useState(false);// 简洁的切换方法const toggleTheme = () => {setIsDark((prev) => !prev);if (!isDark) {document.body.setAttribute('dark-theme', 'dark');} else {document.body.removeAttribute('dark-theme');}};
发现body上加了dark-theme,那么就应该以body为区分,做一些事情
body[tomato-theme='dark'] .content-inner{background-color: yellow;
}
要么单独定义
要么就用一套通用的,在root里把这件事做了,用的时候只用变量
:root {--color-primary-white: green;
}:root body[dark-theme="dark"]{--color-primary-white: yellow;}
可以看到,只要使用
background-color: var(--color-primary-white);
就有效了
参考
https://juejin.cn/post/7301959466399465526
https://juejin.cn/post/7242284648021164091?from=search-suggest