首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检查reactjs中的pariticular fileExists

如何检查reactjs中的pariticular fileExists
EN

Stack Overflow用户
提问于 2018-01-15 16:48:46
回答 1查看 17.2K关注 0票数 11

我正在用React js开发一个应用程序,我在检查目录中是否存在特定的文件时遇到了问题。实际上,我有一个头部组件,即Header.js,它是一个公共头部。但对于一些客户端,我必须根据他们的要求更改头部。为此,我必须创建一个带有客户端id的文件夹,然后将该客户端的新头组件存储在该目录中。现在,我必须在运行时检查特定客户端的头部是否存在,然后显示该客户端的特定头部,否则显示公共头部。我还必须做一些其他客户特定的组件,即页脚,旁注或节等,为一些特定的特定客户根据他们的要求。但是我无法在react中检查特定的组件/文件是否存在??

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-15 21:39:28

您可以尝试要求您的文件,然后根据结果显示正确的组件。

代码语言:javascript
复制
const tryRequire = (path) => {
  try {
   return require(`${path}`);
  } catch (err) {
   return null;
  }
};

然后使用它:

代码语言:javascript
复制
render() {
 const Header = tryRequire('yourPath') ? tryRequire('yourPath').default 
   : DefaultHeader;

 return (
   <Header />
 );
}

还有另一种使用React.lazy的方法,但要做到这一点,您需要创建一个位于项目根目录下的组件(如果您使用的是Create React App,则会将其放置在./src/DynamicImport.js中)。

逻辑如下:

代码语言:javascript
复制
import React, { Suspense, useState, useEffect, lazy } from 'react';

const importCompo = (f, defaultComponentPath) =>
  lazy(() =>
    import(`./${f}`).catch((err) => {

    // Simulate behaviour in Strapi
    // Lazy only support default export so there's a trick to do here 
       when using a library that does not have a default export
    // The example here uses the strapi-helper-plugin package
    if (defaultComponentPath === 'strapi-helper-plugin') {
      return import('strapi-helper-plugin').then((module) => {
        const { Button } = module;

        return {
          // Here's the trick
          // I am creating a new component here
          default: () => <Button primary>Something</Button>,
        };
      });
   }

  return import(`${defaultComponentPath}`);
 }),
);

const DynamicImport = ({ filePath, defaultComponentPath, ...rest }) => {
  const [module, setModule] = useState(null);

  useEffect(() => {
    const loadCompo = () => {
      const Compo = importCompo(filePath, defaultComponentPath);

      setModule(<Compo {...rest} />);
    };

    loadCompo();
  }, []);

  return <Suspense fallback="loading">{module}</Suspense>;
};

DynamicImport.defaultProps = {
  // defaultComponentPath: './components/DefaultCompo',
  defaultComponentPath: 'strapi-helper-plugin',
};

export default DynamicImport;

然后使用它:

代码语言:javascript
复制
const MyCompo = props => {
  return (
    <DynamicImport
      filePath="./components/Foo"
      defaultComponentPath="./components/DefaultCompo"
    />
  );
};
票数 21
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48259512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档