Create-react-appプロダクション環境でAnt Designのダークテーマとライトテーマを動的に切り替えるにはどうすればよいですか?
app.jsx
import { Button, Select } from 'antd';
import { ThemeProvider, useTheme } from 'antd-theme';
import React from 'react';
import ReactDOM from 'react-dom';
import { SketchPicker } from 'react-color';
const initialTheme = {
name: 'default',
variables: { 'primary-color': '#00ff00' },
};
const ThemeSelect = () => {
const [{ name, variables, themes }, setTheme] = useTheme();
return (
<>
<Select
style={{ width: 100 }}
value={name}
onChange={
(theme) => setTheme({ name: theme, variables })
}
>
{
themes.map(
({ name }) => (
<Select.Option key={name} value={name}>
{name}
</Select.Option>
)
)
}
</Select>
<SketchPicker
color={variables['primary-color']}
onChange={(value) => {
// Will update all css attributes affected by primary-color
setTheme({ name, variables: { 'primary-color': value.hex } });
}}
/>
</>
);
};
const App = () => {
const [theme, setTheme] = React.useState(initialTheme);
return (
<ThemeProvider
theme={theme}
onChange={(value) => setTheme(value)}
>
<ThemeSelect />
<Button type="primary">Button</Button>
</ThemeProvider>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
config-overrides.js
const { override, fixBabelImports, addLessLoader, addPostcssPlugins, adjustStyleLoaders, addWebpackPlugin } = require('customize-cra');
const AntdThemePlugin = require('antd-theme/plugin');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: true,
}),
addLessLoader({
javascriptEnabled: true,
}),
adjustStyleLoaders(
(loaders) => {
loaders.use[0] = {
loader: AntdThemePlugin.loader
}
}
),
addWebpackPlugin(
new AntdThemePlugin({
themes: [
{
name: 'dark',
filename: require.resolve('antd/lib/style/themes/dark.less'),
},
{
name: 'compact',
filename: require.resolve('antd/lib/style/themes/compact.less'),
},
],
})
),
);
それがあなたの問題を解決するかどうかを見てください。私はこれを使用していませんが、私には有望に見えます。プレイグラウンド: https://antd-live-theme.firebaseapp.com/ Github URL: https://github.com/mzohaibqc/antd-theme-generator
メインHTMLファイルに次の行を追加します
<link rel="stylesheet/less" type="text/css" href="/color.less" />
<script>
window.less = {
async: false,
env: 'production'
};
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js"></script>
これで、このような.less変数を更新して色を更新できます
window.less.modifyVars({
'@primary-color': '#0035ff'
})
お役に立てれば!