javascript - React HOC 有条件地渲染组件
问题描述
我正在使用 antd 组件,我需要使用基于用户有条件地呈现元素的 HOC 来呈现组件。这是我的 HOC:
export const withAuth = Component => props => {
const { isAdmin } = useAppContext();
return isAdmin ? <Component {...props} /> : null;
};
基本上如果是用户isAdmin
,则渲染组件。我的问题是当我使用该组件时。
import { Button } from 'antd';
import {withAuth} from 'utils'
const App = () => {
const AddAdminBtn = withAuth(Button);
return (
<div>
<AddAdminBtn />
</div>
)
}
如果我可以<AddAdminBtn />
像这样向组件添加道具,那将是理想的<AddAminBtn onChange={} type="link" title="" />
。但这不起作用我不知道为什么。为了使它工作,我必须做的是在声明 HOC 之前用这些道具声明一个按钮,并将该函数传递给 hoc。这可以将道具传递给 AddAdminBtn 吗?
解决方案
You can do in this way
const WithAuth = ({ children }) => {
return true ? <div>authenticathed {children}</div>: <div>unauthenticathed {children}</div>;
};
const Button = (props) => {
return <button {...props}>button</button>;
};
export default function App() {
return (
<div className="App">
<WithAuth>
<Button
onClick={() => alert('hola')}
/>
</WithAuth>
</div>
);
}
推荐阅读
- html - Bootstrap 4轮播图像不覆盖其他图像
- security - F5 负载均衡器拒绝 SHA256 加密算法密码套件?
- c++ - CMake - 将调用的命令行作为 CMake 中的 var 获取
- database - 使用 typeORM 搜索早于日期的数据
- python - 使用 Adobe Reader 命令使用 python 操作 PDF
- c++ - 返回一个字符数组
- ios - 如何将 iOS 项目和字体大小缩放为屏幕大小
- node.js - Sequelize:在日期上添加一天不起作用
- angular - msal.js angular 6 SPA 回调和错误处理
- excel - VBA 循环:自动填写 Web 表单