简体   繁体   English

如何通过条件禁用组件?

[英]How do I disable a component through a condition?

I have a condition (isOnFullDomain()) that returns true , if I am in this condition, the Component can't load.我有一个条件(isOnFullDomain())返回true ,如果我处于这种情况,则组件无法加载。

This is the code i am using:这是我正在使用的代码:

import Component from 'components/Component';

useEffect(() => {
    Component();
    if (isOnFullDomain()) {
      console.log('remove Component');
    }
  }, [path]);

I really need to remove the component once it's loaded, if I load it once, it's showing up on the screen.我真的需要在加载后删除该组件,如果我加载一次,它就会显示在屏幕上。

I need something similar to:我需要类似的东西:

if (isOnFullDomain()) {
  Component().remove;
}

Any idea how I can fix it?知道我该如何解决吗?

You should be able to achieve that by using JSX, rather than react hooks - usually hooks are move towards data management, react to some value updates and do something about it.您应该能够通过使用 JSX 而不是反应钩子来实现这一点——通常钩子转向数据管理,对某些值更新做出反应并对此做一些事情。

In this case I imagine you have a render method that uses your Component .在这种情况下,我想您有一个使用Componentrender方法。 Hence something like this would make the Component not appear in the page.因此,这样的事情会使Component不会出现在页面中。

import Component from 'components/Component';
// ...
const shouldRenderComponent = !isOnFullDomain();

return (
  {shouldRenderComponent && <Component />
);

Sidenote: if you don't want to load the Component code internally, then you might want to have a look at the import statement and bundle splitting in order to "lazy load" that component.旁注:如果您不想在内部加载Component代码,那么您可能需要查看导入语句和包拆分以“延迟加载”该组件。

In the component where you are rendering this component, you could conditionally render it, by doing something like this.在您渲染此组件的组件中,您可以通过执行类似操作来有条件地渲染它。

return(...
{!isOnFullDomain() && <ComponentToBeRendered/>}
...
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM