我如何在React的<ListItem>
上设置条件?如果角色不是管理员,则将其隐藏。
const isAdmin = useSelector((state) => state.auth.is_admin);
const drawer = (
<div>
<Divider />
<List>
{[
{
id: 1,
text: 'Products',
url: `/products`,
access: false,
icon: <DashboardIcon/>,
},
{
id: 2,
text: 'Settings',
url: `/settings`,
access: true,
icon: <AssignmentTurnedInIcon/>,
},
].map((obj, index) => (
<ListItem button key={obj.id} onClick={() => props.history.push(obj.url)} {isAdmin === obj.access}>
<ListItemIcon>{obj.icon}</ListItemIcon>
<ListItemText
disableTypography
primary={
<Typography type="body1" style={{ color: '#FFFFFF' }}>
{obj.text}
</Typography>
}
/>
</ListItem>
))}
</List>
<Divider />
</div>
);
您可以使用三元运算符。检查isAdmin
是否为true
,然后渲染组件,其他情况下仅包含null
。或者,如果您还有其他条件,例如isAdmin === 'admin'
,请使用它。
尝试以下操作:
return <>
{
isAdmin ?
<ListItem button key={obj.id} onClick={() => props.history.push(obj.url)} />
: null
}
<>
显然,为了示例,我删除了其他组件。但这为您提供了如何继续进行操作的想法。
+ 1建议:
[isAdmin
清楚地向我显示了必须为boolean
的值,如果您将其检查为具有值role
的字符串,则不同的命名可能更像userRole
或"admin"
。
我希望这会有所帮助!
const isAdmin = useSelector((state) => state.auth.is_admin);
const drawer = (
<div>
<Divider />
<List>
{[
{
id: 1,
text: 'Products',
url: `/products`,
access: false,
icon: <DashboardIcon/>,
},
{
id: 2,
text: 'Settings',
url: `/settings`,
access: true,
icon: <AssignmentTurnedInIcon/>,
},
].map(obj => isAdmin === obj.access? (
<ListItem button key={obj.id} onClick={() => props.history.push(obj.url)}>
<ListItemIcon>{obj.icon}</ListItemIcon>
<ListItemText
disableTypography
primary={
<Typography type="body1" style={{ color: '#FFFFFF' }}>
{obj.text}
</Typography>
}
/>
</ListItem>: ''
))}
</List>
<Divider />
</div>
);
您可以编写如下代码:
const isAdmin = useSelector((state) => state.auth.is_admin);
const ListItem = {[
{
id: 1,
text: 'Products',
url: `/products`,
access: false,
icon: <DashboardIcon/>,
},
{
id: 2,
text: 'Settings',
url: `/settings`,
access: true,
icon: <AssignmentTurnedInIcon/>,
},
].map((obj, index) => (
obj.access === false && isAdmin || obj.access === true?
<ListItem button key={obj.id} onClick={() => props.history.push(obj.url)} {}>
<ListItemIcon>{obj.icon}</ListItemIcon>
<ListItemText
disableTypography
primary={
<Typography type="body1" style={{ color: '#FFFFFF' }}>
{obj.text}
</Typography>
}
/>
</ListItem>
: ''
))}
const drawer = (
<div>
<Divider />
<List>
{ListItem}
</List>
<Divider />
</div>
);
access is false and isAdmin is true
为真,如果菜单是管理员角色,而obj.access === true
为真,则菜单为全部。
obj.access === false && isAdmin || obj.access === true