reactjs - 反应 HOC 包装器
问题描述
我不确定我是否做对了,但我想制作一个 hoc,它会根据用户是否是管理员来显示组件。这是我的 HOC:
export const WithUser = (Component) => (props) => {
if (props.admin) {
return <Component {...props} />;
}
return null;
};
使用时出现错误Functions are not valid as a React child.
对我来说没有意义。
我想像这样使用它:
<WithUser admin>
<button>Hi</button>
</WithUser>
但我得到了那个错误。也许我没有正确使用 HOC。我只想包装用户需要成为管理员才能查看的组件
解决方案
你可以从 react 官网看一下HOC 文档
将您的代码修改为:
// admin prop should be obtained from within WithUser or other places such as redux store or react context
export const WithUser = (Component) => (props) => {
if (props.admin) {
return <Button {...props} />;
}
return null;
};
class Button extends React.Component {
render() {
return <button>Hi</button>
}
}
export default WithUser(Button)
推荐阅读
- scala - Scala — 特定格式的 GroupBy 列
- angular - 错误 TS2322:类型“数字”不可分配给类型“字符串”
- c++ - 我最近没有声明时无法生成默认构造函数
- c# - Azure 文件存储 - 复制时阻止
- javascript - 如何在打字稿中动态创建输入类型文本
- qt - 使用专有编解码器构建 QtWebEngine 5.9.1
- python - 在 Ubuntu 18.04 上安装 OpenCV 3.4.2
- python - 抓取修改后的文件名python
- python - Python3 TypeError:采用 1 个位置参数,但给出了 2 个
- javascript - 使用 JS 添加选择>选项作为列表项