簡體   English   中英

React HOC 有條件地渲染組件

[英]React HOC to conditionally render a component

我正在使用 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>
  )
}

如果我可以像<AddAminBtn onChange={} type="link" title="" />這樣向<AddAdminBtn />組件添加道具,那將是理想的。 但這不起作用我不知道為什么。 我必須做的是在聲明 HOC 之前用這些道具聲明一個按鈕,並將 function 傳遞給 hoc。 這可以將道具傳遞給 AddAdminBtn 嗎?

你可以這樣做

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM