乐闻世界logo
搜索文章和话题

How to disable click event for SubMenu in Ant Design?

1个答案

1

In Ant Design, if you want to disable click events on submenu items, there are two main methods to achieve this. Below are the specific steps and code examples:

Method One: Control Using the onClick Event

You can add logic to the onClick event of the Menu component to check and prevent click events on specific submenu items. The key is to use the stopPropagation method of the event object to prevent the event from propagating further.

Example Code:

jsx
import React from 'react'; import { Menu } from 'antd'; const { SubMenu } = Menu; class App extends React.Component { handleClick = (e) => { if (e.key === 'subItem1') { e.domEvent.stopPropagation(); // Prevent click event from propagating upward console.log('Submenu item click event has been disabled'); return; // Return early to prevent further processing } // Handling for other menu items console.log('Clicked menu item:', e.key); }; render() { return ( <Menu onClick={this.handleClick}> <SubMenu key="sub1" title="Main Menu 1"> <Menu.Item key="subItem1">Non-clickable submenu item</Menu.Item> <Menu.Item key="subItem2">Submenu item 2</Menu.Item> </SubMenu> <Menu.Item key="mainItem1">Main menu item 1</Menu.Item> </Menu> ); } } export default App;

Method Two: Modify Using CSS Styles

Another approach is to disable click events on submenu items by modifying CSS styles. You can add a class name to specific menu items and set the pointer-events property of that class to none in CSS. This will ignore all mouse events for the menu item.

Example Code:

jsx
import React from 'react'; import { Menu } from 'antd'; import './App.css'; // Import CSS file const { SubMenu } = Menu; class App extends React.Component { render() { return ( <Menu> <SubMenu key="sub1" title="Main Menu 1"> <Menu.Item key="subItem1" className="disabled-item">Non-clickable submenu item</Menu.Item> <Menu.Item key="subItem2">Submenu item 2</Menu.Item> </SubMenu> <Menu.Item key="mainItem1">Main menu item 1</Menu.Item> </Menu> ); } } export default App;
css
/* App.css */ .disabled-item { pointer-events: none; /* Disable mouse events */ color: gray; /* Optional: change color to indicate disabled state */ }

By using either of these methods, you can effectively disable click events on submenu items in Ant Design. The choice depends on your specific requirements and preferences.

2024年8月9日 20:51 回复

你的答案