admin管理员组文章数量:1410724
I've seen that we can dynamically import default ponents using:
const MyComponent = React.lazy(() => import('./myPath'));
We can render it just by using <MyComponent/>
. To my understanding this method only allows for the importing of default ponents from the specified path.
My question is: How can we dynamically import other ponents or functions that are exported from myPath
(non default)?
I've seen that we can dynamically import default ponents using:
const MyComponent = React.lazy(() => import('./myPath'));
We can render it just by using <MyComponent/>
. To my understanding this method only allows for the importing of default ponents from the specified path.
My question is: How can we dynamically import other ponents or functions that are exported from myPath
(non default)?
1 Answer
Reset to default 8React.lazy currently supports only default exports. A suggested solution from the docs is:
If the module you want to import uses named exports, you can create an intermediate module that reexports it as the default. This ensures that tree shaking keeps working and that you don’t pull in unused ponents.
For example
// ManyComponents.js
export const MyComponent = /* ... */;
export const MyUnusedComponent = /* ... */;
// MyComponent.js
export { MyComponent as default } from "./ManyComponents.js";
// MyApp.js
import React, { lazy } from 'react';
const MyComponent = lazy(() => import("./MyComponent.js"));
Another solution is some added boilerplate like below. This way, there is no need for an intermediary ponent:
const MyComponent = React.lazy(() =>
import('./MyComponent').then((module) => ({ default: module.MyComponent }))
)
Alternately, you can use react-lazily
like so:
const { MyComponent } = lazily(() => import('./MyComponent'))
本文标签: javascriptReactDynamically Import NonDefault Component or FunctionStack Overflow
版权声明:本文标题:javascript - React - Dynamically Import Non-Default Component or Function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744814160a2626598.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论