ps:使用了 redux react-redux 。如果不想使用。可以去掉。自己从别的地方获取 有权限的id集合。
tsx:(主要组件)
import { RootState } from "@/store";
import React, { ReactNode } from "react";
import { useSelector } from "react-redux";
type Props = {
aId: string;
children: ReactNode;
};
function AuthCom({ aId, children }: Props) {
// 从仓库获取有权限的id集合,已经整理了数据,格式为 ['1','2',...]
const arr = useSelector((state: RootState) => state.A4Role.A4RoleAll);
// 如果 仓库 中的 id集合 找到了 你传入的id(或者传入的id为-1),说明有权限,返回 children ,否则返回null(不渲染)
return <>{arr.find((v) => v === aId) || aId === "-1" ? children : null}</>;
}
const MemoAuthCom = React.memo(AuthCom);
export default MemoAuthCom;
使用
<AuthCom aId="1104">
//里面书写任意组件,或者t(j)sx代码
</AuthCom>
完事。有手就会,超级简单。
之前发表的一篇文章# react二次封装antd Button,实现鉴权按钮功能。弄得比较复杂。
用以上方法就可以 简单 实现。