gpt4 book ai didi

javascript - 如何基于依赖项导入 React 组件?

转载 作者:行者123 更新时间:2023-11-30 11:58:43 25 4
gpt4 key购买 nike

我第一次使用 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';
}

我怎样才能做到这一点?

最佳答案

您不能动态导入模块,但是您可以像通常的模块一样导入它们

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 />;
}

关于javascript - 如何基于依赖项导入 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37209996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com