Reason 1.

The general design generates the project icon file through iconfont and dynamically changes the icon display by changing the icon code. Since the latest design is not icon but multiple SVG images, the rendered images can be changed through different conditional judgments.

For example, the icon like SVG image on the left, clicked, unclicked and clicked by different themes, unclicked SVG image. Replacing image SRC with code logic can be cumbersome and tedious. You can dynamically change the displayed SVG image by dynamically changing the xlinkHref value of the SVG.

2. Implement

According to the logic above, different menus will have different codes to distinguish them. First, create a map with the code corresponding to the name of the SVG image.

Const iconMap = {/ / collaboration 'XXX. Code. Project. Currency' : 'xiezuo', / / deploy 'XXX. Code. Project. Deploy' : 'bushu', // develop' xxx.code.project.develop': 'kaifa', // test' xxx.code.project.test': 'ceshi', 'xxx.code.project.demand': 'xuqiu', 'xxx.code.site.infra': 'jichu', 'xxx.code.project.doc': 'wendang', // set 'xxx.code.project.setting': 'shezhi', / / organization level management 'xxx.code.org anization. Manager' : 'guanli', / / organization level set 'xxx.code.org anization. Setting' : 'shezhi', // platform layer manage 'xx.code.site.manager': ', // platform layer set' xx.code.site.setting': 'shezhi', / / the platform layer market 'XXX. Code. The site. The market' : 'shichang, / / the platform layer hzero' XXX. Code. Site. Hzero. Manager ': 'hzero', // user layer individual 'xxx.code.person.setting': 'shezhi',};Copy the code

Save the SVG image to the project, using the deployment menu as an example

Create requiresvgResources.js file to import SVG images in bulk

const req = require.context('.. /header/style/icons', false, /\.sprite.svg$/); const requireAll = (requireContext) => requireContext.keys().map(requireContext); requireAll(req);Copy the code

Create a menusideicon.js file to replace SVG images with different SVgname names passed in

import React from 'react';
export default ({ name }) => (  
    <svg style={{ height: 30 }} aria-hidden="true">    
        <use xlinkHref={`#${name}`} />  
    </svg>
);
Copy the code

In the index. In js

import './RequireSvgResources'; import MenuSideIcon from './MenuSideIcon'; const menuCode = 'xxx.code.project.deploy'; export default () => { const renderMenuSideIconName = (code) => { const str = IconMap[code]; If (click) {return '${STR}click.sprite'; } else if (new theme) {return '${STR}new.sprite'; } return `${str}.sprite`; } return ( <MenuSideIcon name={renderMenuSideIconName(menuCode)} /> )}Copy the code