反应 HOC 以有条件地渲染组件

时间:2021-04-14 15:47:31

标签: javascript reactjs

我正在使用 antd 组件,我需要使用 HOC 来呈现组件,该 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?

1 个答案:

答案 0 :(得分:0)

你可以这样做

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>
  );
}