You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CoreUI React侧边栏点击时传权限Props控制组件按钮状态

Solution for CoreUI Sidebar + React/Redux Permission Control

Let's work through this step by step to get your permission-based button enable/disable logic up and running smoothly:

1. Ensure Permissions Live in Your Redux Store

First, make sure the permissions you fetch from the database are stored in your Redux state. If you haven't set this up yet, here's a quick example:

// actions/permissionsActions.js
export const fetchPermissions = () => async dispatch => {
  const res = await fetch('/api/user-permissions'); // Replace with your actual API endpoint
  const permissions = await res.json();
  dispatch({ type: 'SET_PERMISSIONS', payload: permissions });
};

// reducers/permissionsReducer.js
const initialState = {
  userPermissions: []
};

export default (state = initialState, action) => {
  switch(action.type) {
    case 'SET_PERMISSIONS':
      return { ...state, userPermissions: action.payload };
    default:
      return state;
  }
};

Then connect your main component to Redux to access these permissions:

import { connect } from 'react-redux';
import { fetchPermissions } from './actions/permissionsActions';

class YourMainComponent extends Component {
  componentDidMount() {
    this.props.fetchPermissions(); // Fetch permissions when the app loads
  }

  // ... your existing render code
}

const mapStateToProps = state => ({
  userPermissions: state.permissions.userPermissions
});

export default connect(mapStateToProps, { fetchPermissions })(YourMainComponent);

2. Pass Permissions to Route Components

Update your route rendering in the main component to pass the userPermissions prop to every route's component. Modify the Route render function like this:

{routes.map((route, idx) => {
  return route.component ? (
    <Route
      key={idx}
      path={route.path}
      exact={route.exact}
      name={route.name}
      render={(props) => (
        // Inject permissions into the component props
        <route.component {...props} permissions={this.props.userPermissions} />
      )}
    />
  ) : (
    <Redirect from="*" to="/dashboard" />
  );
})}

3. (Optional) Hide Unauthorized Sidebar Items

If you also want to hide sidebar items the user doesn't have access to, add permission requirements to your nav.js items first:

// nav.js
export default {
  items: [
    // ... existing items
    {
      name: "sub menu 1",
      url: "/login", // Note: You might want to fix this URL to match your actual component path
      icon: "cui-people",
      requiredPermission: "can_access_submenu1" // Add this field
    },
    // ... other items
  ]
};

Then filter the nav config before passing it to AppSidebarNav in your main component:

// Helper function to filter authorized nav items
const filterAuthorizedNavItems = (items, permissions) => {
  return items.filter(item => {
    // Keep items with no permission requirement
    if (!item.requiredPermission) return true;
    // Keep items where the user has the required permission
    return permissions.includes(item.requiredPermission);
  }).map(item => {
    // Recursively filter child items if present
    if (item.children) {
      return { ...item, children: filterAuthorizedNavItems(item.children, permissions) };
    }
    return item;
  });
};

// Inside your render() method
const filteredNavs = {
  items: filterAuthorizedNavItems(_navs.items, this.props.userPermissions)
};

// Pass the filtered navs to AppSidebarNav
<AppSidebarNav navConfig={filteredNavs} {...this.props} router={router} />

4. Control Button State in Your Target Component

Finally, in the component linked to "sub menu 1", use the permissions prop to toggle the button's disabled state:

// SubMenu1Component.jsx
import React from 'react';

const SubMenu1Component = ({ permissions }) => {
  // Check if the user has the permission to use the register button
  const canRegister = permissions.includes("can_create_registration");

  return (
    <div className="container mt-4">
      <h2>Sub Menu 1</h2>
      <button 
        type="button" 
        className="btn btn-primary"
        disabled={!canRegister}
      >
        Register User
      </button>
    </div>
  );
};

export default SubMenu1Component;

Now when you click the sidebar menu item, the corresponding component will receive the permissions prop, and your register button will automatically enable/disable based on the user's database-defined permissions.

内容的提问来源于stack exchange,提问作者shevin fernando

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:45:11