[英]React: dynamic import jsx
此問題與將JSX文件動態導入React有關。
基本上我們有一個主要組件,它根據存儲在數據庫中的結構動態呈現其他組件。 動態組件存儲在子目錄“./Components”中。 我們將此靜態定義為:
import CompA from './Components/CompA';
import CompB from './Components/CompB';
var components = {
'CompA': CompA,
'CompB': CompB
}
我們使用以下方式渲染它們
var type = 'CompA'
var Component = components[type];
...
<Component />
雖然這很好用但對我們來說有點太靜態了。 我們有100多個組件(CompA / CompBs)並靜態定義它們不起作用。
是否可以在“./Compontents”中導入所有JSX文件並填充components-array?
而且,如果我們可以將“./Components”路徑作為主要組件的支柱發送,那真正(真正)好的將是什么。 主要組件將使用此路徑導入.jsx文件。 像這樣:
<MainComponent ComponentPath="./SystemComponents">
將使用“./SystemComponents”作為.JSX文件的路徑,並且:
<MainComponent ComponentPath="./UserComponents">
將使用“./UserComponents”作為導入路徑。
如果有一個包含內容的components / index.js呢:
export CompA from "./comp_a";
export CompB from "./comp_b";
然后你做:
import * as Components from "./components"
然后你會用作:
<Components.CompA />
<Components.CompB />
...
希望這可以幫助。
我懷疑你在通過組件道具發送路徑時可以加載任何東西,然后應該在React組件生命周期方法內部加載文件,這不是我建議的。
為了補充@ gor181的答案,我可以補充一點, export
必須是這樣的:
export { default as CompA } from "./comp_a"; export { default as CompB } from "./comp_b";
希望這可能會有所幫助。
從React 16.6.0開始 ,我們可以延遲加載組件並按需調用它們。
路由
// We pass the name of the component to load as a param
<Switch>
…
<Route path="/somewhere/:componentName" component={MyDynamicComponent} />
</Switch>
意見/ index.js
import { lazy } from 'react';
const SomeView = lazy(() => import('./SomeView'));
const SomeOtherView = lazy(() => import('./SomeOtherView'));
export { SomeView, SomeOtherView };
MyDynamicComponent.js
import React, { Suspense, Component } from 'react';
import { PropTypes } from 'prop-types';
import shortid from 'shortid'; // installed separately via NPM
import * as Views from './views';
class MyDynamicComponent extends Component {
render() {
const {
match: {
params: { componentName },
},
} = this.props;
const Empty = () => <div>This component does not exist.</div>;
const dynamicComponent = (() => {
const MyComponent = Views[`${componentName}View`]
? Views[`${componentName}View`]
: Empty;
return <MyComponent key={shortid.generate()} />;
})();
return (
<>
<Suspense fallback={<div>Loading…</div>}>{dynamicComponent}</Suspense>
</>
);
}
}
MyDynamicComponent.propTypes = {
match: PropTypes.shape({
params: PropTypes.shape({
componentName: PropTypes.string.isRequired,
}),
}),
};
export default MyDynamicComponent;
用法
{items.map(item => (
<NavLink to={`/somewhere/${item.componentName}`}>
{item.name}
</NavLink>
))}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.