gpt4 book ai didi

reactjs - 如何在react js中检查特定文件是否存在

转载 作者:行者123 更新时间:2023-12-03 13:25:34 29 4
gpt4 key购买 nike

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

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com