#reactjs #material-ui #role-based-access-control
#reactjs #материал-пользовательский интерфейс #управление доступом на основе ролей
Вопрос:
Я пытаюсь внедрить меню доступа на основе ролей в свое приложение React и использовал панель навигации из пользовательского интерфейса Material. У меня это работало ранее, но поскольку я удалил перехваты, когда изменил его на компонент класса, я не могу понять, что он отображается неправильно, и я не могу заставить выпадающий список работать.
У меня также есть проблема, поскольку в моем Redux есть ‘user’ json, и по какой-то причине componentDidMount не позволяет мне извлекать номер роли пользователя, чтобы отобразить правильные параметры для определенной роли.
Сообщения об ошибках консоли
Warning: Failed prop type: The prop `open` is marked as required in `ForwardRef(Menu)`, but its value is `null`
Warning: Failed prop type: The prop `open` is marked as required in `ForwardRef(Popover)`, but its value is `null`.
Warning: Failed prop type: The prop `open` is marked as required in `ForwardRef(SimpleBackdrop)`, but its value is `null`.
Warning: Failed prop type: The prop `open` is marked as required in `Unstable_TrapFocus`, but its value is `null`.
Warning: Failed prop type: Material-UI: You are providing an onClick event listener to a child of a button element.
Firefox will never trigger the event.
scubaNavBar.component.js
class ScubaNavbar extends Component {
constructor(props) {
super(props);
this.logOut = this.logOut.bind(this);
this.state = {
showUserLevelAccess: false,
showSchoolLevelAccess: false,
showAdminLevelAccess: false,
user: undefined,
anchorEl: null,
mobileMoreAnchorEl: null,
isMenuOpen: null,
isMobileMenuOpen: null,
};
history.listen((location) => {
props.dispatch(clearMessage());
});
}
componentDidMount() {
const user = this.props.user;
if (user) {
this.setState({
currentUser: user,
showUserLevelAccess: user.userRoles === 1,
showSchoolLevelAccess: user.userRoles === 2,
showSiteAdminLevelAccess: user.userRoles === 3,
});
}
}
logOut() {
this.props.dispatch(logout());
}
render() {
const {
// current user gives specific user details
currentUser,
// levels give role access
showUserLevelAccess,
showSchoolLevelAccess,
showSiteAdminLevelAccess,
} = this.state;
const { classes } = this.props;
**const handleProfileMenuOpen =() => {
this.setState({anchorEl: this.currentTarget, open: Boolean(this.currentTarget)});
};
const handleMenuClose = () => {
this.setState({anchorEl: this.currentTarget === null});
};
const handleMobileMenuOpen = () => {
this.setState({mobileMoreAnchorEl: this.currentTarget, open: Boolean(this.currentTarget)});
};
const handleMobileMenuClose = () => {
this.setState({mobileMoreAnchorEl: this.currentTarget === null});
};**
const menuId = 'dark-search-account-menu';
const renderMenu = (
<Menu
anchorEl={this.state.anchorEl}
anchorOrigin={{vertical: 'top', horizontal: 'right'}}
id={menuId}
keepMounted
transformOrigin={{vertical: 'top', horizontal: 'right'}}
open={this.state.isMenuOpen}
onClose={handleMenuClose}>
Ответ №1:
Согласно документу, значение, которое получает open prop, должно быть логическим. Итак, просто назначьте isMenuOpen: false
в своем состоянии, и все будет работать нормально.
Ответ №2:
Вы можете прочитать сообщения консоли, в которых в значительной степени все сказано. в нем говорится, что у вас отсутствует open prop как логическое значение, которое отвечает за отображение вашего выпадающего списка или нет.
<Menu
nchorEl={this.state.anchorEl}
anchorOrigin={{vertical: 'top', horizontal: 'right'}}
id={menuId}
keepMounted
transformOrigin={{vertical: 'top', horizontal: 'right'}}
open={this.state.isMenuOpen} // initially you are setting this null on your constructor change it to false.
onClose={handleMenuClose}>
```
And second warning says you are attaching event to a children of a button. Move that onclick handler to your button or your menu list item.