react-router+antD/ How to highlight a menu item when press back/forward button?

后端 未结 6 2224
[愿得一人]
[愿得一人] 2021-02-12 17:54

I create a menu and want to highlight the item which i choose,and i did it. But when i press back/forward button,the menu item don\'t highlight. What should i do?

I ha

6条回答
  •  走了就别回头了
    2021-02-12 18:00

    @Nadun's solution works for paths that don't contains arguments. If you're however using arguments in your routes, like me, here's a solution that should work for any route path, including /users/:id or crazy stuff like /users/:id/whatever/:otherId. It uses react-router's matchPath API, which uses the exact same logic as the Router component.

    // file with routes
    export const ROUTE_KEYS = {
        ROOT: "/",
        USER_DETAIL: "/users/:id",
    };
    
    export const ROUTES = {
        ROOT: {
            component: Home,
            exact: true,
            key: ROUTE_KEYS.ROOT,
            path: ROUTE_KEYS.ROOT,
        },
        USER_DETAIL: {
            component: Users,
            key: ROUTE_KEYS.USER_DETAIL,
            path: ROUTE_KEYS.USER_DETAIL,
        },
    };
    

    .

    // place within the App component
    
        
            
            
                
                    {Object.values(ROUTES).map((route) => (
                        
                    ))}
                
            
        
    
    

    .

    // MyMenu component
    const getMatchedKey = (location) =>
        (
            Object.values(ROUTES).find((route) =>
                matchPath(location.pathname, route)
            ) || {}
        ).path;
    
    const MyMenu = ({ location }) => {
        return (
            
                
                    
                                
                                Home
                            
                        }
                    >
                        
                            
                            
                                Some subitem
                            
                        
                    
                    
                                
                                Users
                            
                        }
                    >
                        
                            
                            
                                User detail
                            
                        
                    
                
            
        );
    };
    
    export default withRouter(MyMenu);
    

提交回复
热议问题