The project architecture
create-react-app + antDesign + redux
instructions
The company needs to develop an online skin changing function. Considering the complexity, we still think that it is possible to directly change the primary value of antDesign through the plug-in, so that the color of antDesign components can be changed globally by changing a color. Here, antD-Theme-Generator is used to achieve ‘pro-test effectiveness
The installation
antd-theme-generator
‘needs to be used with less
directory
Add color.js to the root directory
const path = require('path');
const { generateTheme } = require('antd-theme-generator');
const options = {
stylesDir: path.join(__dirname, './src/styles'),
antDir: path.join(__dirname, './node_modules/antd'),
varFile: path.join(__dirname, './src/styles/variables.less'),
mainLessFile: path.join(__dirname, './src/styles/index.less'), themeVariables: [// themeVariables that need to be dynamically switched'@primary-color'.'@secondary-color'.'@text-color'.'@text-color-secondary'.'@heading-color'.'@layout-body-background'
],
indexFileName: 'index.html',
outputFilePath: path.join(__dirname, './public/color.less') // The theme variable file introduced by the page}; generateTheme(options) .then(less => { console.log('Theme generated successfully');
})
.catch(error => {
console.log('Error', error);
});
Copy the code
Add style/index.less+style/ variable. less to the SRC folder
The index.less file is empty
The variables. Less documents
@import '~antd/lib/style/themes/default.less'; @primary-color: // add a variable to the antd file.'# 202777';
@layout-header-padding: '0px';
:root {
--PC: @primary-color;
}
Copy the code
Add global LESS configuration to the index. HTML file
Add global less variable configuration to index.html to make the modifyVars method of less available globally, override variables in default.less when switching themes:
<body>
<link
rel="stylesheet/less"
type="text/css"
href="%PUBLIC_URL%/color.less"
rel="external nofollow"
/>
<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>
<div id="root" style="height: 100%;"></div>
</body>
Copy the code
Package. json file modification command
"scripts": {
"start": "node color && node scripts/start.js"."build": "node color && node scripts/build.js"."test": " node color && node scripts/test.js"
},
Copy the code
Switching method
Change @primary-color color to change theme color, which can be stored in storage, switch page can call this method first
getTheme = data => {
window.less
.modifyVars({
'@primary-color': this.state.styleList[data].color,
'@layout-header-padding': '0px'
})
.then(() => {
this.setState({ style: data });
})
.catch(error => {
console.log(error);
});
};
Copy the code