1.目录结构
2.index.js主要内容
import React from 'react'; import PropTypes from 'prop-types'; const prefixCls = 'change-components'; const ChangeComponents = (props) => { const { componentName } = props; const dynamicLoadComponent = (component) => { return require(`../components/${component}/index`).default; }; const DynamicDetail = dynamicLoadComponent(componentName); return ( <div className={prefixCls}> <DynamicDetail /> </div> ); }; ChangeComponents.propTypes = { componentName: PropTypes.string.isRequired }; export default ChangeComponents;
#特殊说明:
require(`../components/${component}/index`).default;
这句话可能有些人的node版本不一样,不需要加.default;
componentName :在引用组件的时候必须传这个参数!