作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 React js 开发一个应用程序,我在检查目录中是否存在特定文件时遇到问题。实际上我有一个 header 组件,即 Header.js 及其通用 header 。但对于某些客户,我必须根据他们的要求更改标题。为此,我必须创建一个包含客户端 ID 的文件夹,然后在该目录中存储该客户端的新 header 组件。现在,我必须检查运行时是否存在特定客户端的 header ,然后显示该客户端的特定 header ,否则显示公共(public) header 。我还必须根据一些特定客户的要求,为他们制作一些其他特定于客户的组件,即页脚、旁白或部分等。但我无法检查 react 特定组件/文件是否存在?
最佳答案
您可以尝试请求您的文件,然后根据结果显示正确的组件。
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"
/>
);
};
关于reactjs - 如何在react js中检查特定文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48259512/
我是一名优秀的程序员,十分优秀!