首页 > 解决方案 > 反应 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。我只想包装用户需要成为管理员才能查看的组件

标签: reactjshigher-order-components

解决方案


你可以从 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)

推荐阅读