简体   繁体   中英

What's the best way to conditionally import a component from another component?

So, the problem is, I have a component A, that should render a component B according to some condition. I could import B at the top and everything will be fine, but If the condition isn't met, I don't want to end up with all B's component code not needing it. The way im doing is:

let B;
if (condition) { B = require('./B.js' }

Does this make sense? Thanks.

The problem is that I'm getting the "Element type is invalid: expected a string" error.

Edit1: I'm using create-react-app Edit2: Solution: let comp; if(condition) { comp = require('./SomeComponent').default; } let comp; if(condition) { comp = require('./SomeComponent').default; }

If you are using Webpack, you can perform a dynamic import along with having that import bundled separately from the component code.

const B = condition && import(/* webpackMode: "lazy-once" */ './b.js')

Otherwise you can simply use dynamic imports:

const B = condition && import('./b.js')

you can try dynamic import? Although it would require using babel/es6+ https://github.com/airbnb/babel-plugin-dynamic-import-node#usage

if(x) {
 import('./B.js').then(B => this.setState({ B })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM