【问题标题】:React HOC to conditionally render a componentReact HOC 有条件地渲染组件
【发布时间】:2021-04-14 15:47:31
【问题描述】:

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

如果我可以像 &lt;AddAminBtn onChange={} type="link" title="" /&gt; 那样向 &lt;AddAdminBtn /&gt; 组件添加道具将是理想的。但这不起作用我不知道为什么。为了使它工作,我必须做的是在声明 HOC 之前用这些道具声明一个按钮,并将该函数传递给 hoc。这可能只是将道具传递给 AddAdminBtn 吗?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你可以这样做

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2019-02-18
      • 2020-05-16
      相关资源
      最近更新 更多