React: dynamic import jsx

后端 未结 3 682
鱼传尺愫
鱼传尺愫 2021-02-04 18:55

This question related to dynamically importing JSX files into React.

Basically we have one main component that dynamically renders other components based on a structure

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 19:36

    As of React 16.6.0, we can lazy-load components and invoke them on-demand.

    The Routing

    // We pass the name of the component to load as a param
    
    
    

    views/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 = () => 
    This component does not exist.
    ; const dynamicComponent = (() => { const MyComponent = Views[`${componentName}View`] ? Views[`${componentName}View`] : Empty; return ; })(); return ( <> Loading…
    }>{dynamicComponent} ); } } MyDynamicComponent.propTypes = { match: PropTypes.shape({ params: PropTypes.shape({ componentName: PropTypes.string.isRequired, }), }), }; export default MyDynamicComponent;

    Usage

    {items.map(item => (
      
        {item.name}
      
    ))}
    

提交回复
热议问题