我正在用React js开发一个应用程序,我在检查目录中是否存在特定的文件时遇到了问题。实际上,我有一个头部组件,即Header.js,它是一个公共头部。但对于一些客户端,我必须根据他们的要求更改头部。为此,我必须创建一个带有客户端id的文件夹,然后将该客户端的新头组件存储在该目录中。现在,我必须在运行时检查特定客户端的头部是否存在,然后显示该客户端的特定头部,否则显示公共头部。我还必须做一些其他客户特定的组件,即页脚,旁注或节等,为一些特定的特定客户根据他们的要求。但是我无法在react中检查特定的组件/文件是否存在??
发布于 2018-01-15 21:39:28
您可以尝试要求您的文件,然后根据结果显示正确的组件。
const tryRequire = (path) => {
try {
return require(`${path}`);
} catch (err) {
return null;
}
};然后使用它:
render() {
const Header = tryRequire('yourPath') ? tryRequire('yourPath').default
: DefaultHeader;
return (
<Header />
);
}还有另一种使用React.lazy的方法,但要做到这一点,您需要创建一个位于项目根目录下的组件(如果您使用的是Create React App,则会将其放置在./src/DynamicImport.js中)。
逻辑如下:
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;然后使用它:
const MyCompo = props => {
return (
<DynamicImport
filePath="./components/Foo"
defaultComponentPath="./components/DefaultCompo"
/>
);
};https://stackoverflow.com/questions/48259512
复制相似问题