【问题标题】:How do I import React component based on a dependancy?如何根据依赖项导入 React 组件?
【发布时间】:2016-09-09 15:36:27
【问题描述】:

我第一次使用 React (babel) 和 jsx 以及 Webpack 来创建我的bundle.js

我已经创建了两个 React 组件 - Header1.jsx 和 Header2.jsx。

如果在 2016 年 7 月 4 日之前 -> 使用 Header1.jsx
如果在 2016 年 7 月 4 日之后 -> 使用 Header2.jsx

要将组件导入 React,我使用的是 index.js:

import SportMenu from './components/SportMenu.jsx';
import NextMatches from './components/NextMatches.jsx';
(...)

基本上我想要一个这样的代码:

var eventStart = new Date('2016-06-10T21:00:00+02:00');
var now = new Date();

if(nowgetDate().getDate() < eventStart.getDate()){
    import EmCountdown from './components/Countdown.jsx';
} else {
    import FocusMenu from './components/FocusMenu.jsx';
}

我怎样才能做到这一点?

【问题讨论】:

    标签: javascript reactjs webpack jsx


    【解决方案1】:

    你不能动态导入模块,但是你可以像往常一样导入它们

    import SportMenu from './components/SportMenu.jsx'; 
    import NextMatches from './components/NextMatches.jsx'; 
    import EmCountdown from './components/Countdown.jsx'; 
    import FocusMenu from './components/FocusMenu.jsx'; 
    

    然后按条件渲染它们

    var eventStart = new Date('2016-06-10T21:00:00+02:00');
    var now = new Date();
    
    if (now < eventStart){
        <EmCountdown />; 
    } else {
        <FocusMenu />;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 2015-11-23
      相关资源
      最近更新 更多