简体   繁体   中英

How do I change the color of selected menu item in Ant Design?

In Ant Design, the default color of a selected menu item is blue, but I want to change the color. Here's some of my code:

 import React from 'react'; import { BrowserRouter as Router, Switch, Route, NavLink, } from 'react-router-dom'; import { Layout, Menu } from 'antd'; import Create from './Create'; import Dashboard from './Dashboard'; import './layout.css'; const { Header, Footer, Sider, Content } = Layout; const { Item } = Menu; function LayoutPage() { return ( <Router> <Layout style={{ minHeight: '100vh' }}> <Sider> <Menu theme='dark' defaultSelectedKeys={['item1']} mode='inline' > <Item key='item1' className='customclass'> <NavLink to='/'> <span>Dashboard</span> </NavLink> </Item> <Item key='item2' className='customclass'> <NavLink to='/create'> <span>Create</span> </NavLink> </Item> </Menu> </Sider> <Layout> <Header style={{ padding: 0, background: '#EBF1FC' }} /> <Content style={{ padding: 24, background: '#EBF1FC', minHeight: 280, }} > <div style={{ padding: 24, background: '#EBF1FC', minHeight: 360 }}> <Switch> <Route exact path='/'> <Dashboard /> </Route> <Route path='/create'> <Create /> </Route> </Route> </Switch> </div> </Content> </Layout> </Layout> </Router> ); } export default LayoutPage;
 .ant-menu.ant-menu-dark .ant-menu-item-selected.customclass { background-color: '#B039CC'; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/antd/4.8.5/antd.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

In the css file you can see me attempting this solution but weirdly it only works if the menu mode is 'horizontal'.

I also tried this method, in which I created my custom Menu component and overrode the ant-menu-item-selected property but that did not work either (i think it's because I also need to use the Item component, which I have to access using my custom Menu component).

 .ant-menu-item-selected {
    background-color: #B039CC !important;
  }

add important

You say this method , it only works if the menu mode is 'horizontal', beacause .ant-menu-horizontal this statement only matches the horizontal mode... you can remove the word horizontal ,and tyr again.,like this:

.ant-menu > .ant-menu-item:hover,
.ant-menu > .ant-menu-submenu:hover,
.ant-menu > .ant-menu-item-active,
.ant-menu> .ant-menu-submenu-active,
.ant-menu > .ant-menu-item-open,
.ant-menu> .ant-menu-submenu-open,
.ant-menu > .ant-menu-item-selected,
.ant-menu > .ant-menu-submenu-selected {
  color: red;
  border-bottom: 2px solid red;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM