首页 > 解决方案 > 使用 require 时的 ReferenceError

问题描述

我正在尝试为此 DateTimePicker jQuery 插件创建一个包装器作为 React 组件。到目前为止它正在工作,但我正在尝试设置它的语言环境,为此我需要从库中导入特定文件。

我正在这样做require('gijgo/js/messages/messages.pt-br'),但是它会引发错误ReferenceError: gj is not defined。该对象gj是导入的require('gijgo/js/gijgo');,我已经尝试过这样做:

const gj = require('gijgo/js/gijgo');
window.gj = gj;
require('gijgo/js/messages/messages.pt-br')

就像我导入 jQuery(库 gijgo 使用它)一样,但它不起作用。

这是我的整个代码:

import React from "react"
import $ from 'jquery'
import 'bootstrap';
import { TextInput } from '../Form/Form'

window.jQuery = $;
window.$ = $;
require('gijgo/js/gijgo');
require('gijgo/js/messages/messages.pt-br')
require('gijgo/css/gijgo.css');

export default class DateTimePicker extends React.Component {
  componentDidMount() {
    this.$dateTimePicker = $(this.dateTimePicker);
    this.$dateTimePicker.on("change", this.props.onChange);
    this.$dateTimePicker.datetimepicker({
      locale: 'pt-br',
      uiLibrary: 'bootstrap4',
      format: 'dd-mm-yyyy HH:MM',
      modal: true,
      footer: true
    });
  }

  componentWillUnmount() {
    this.$dateTimePicker.destroy("datetimepicker");
  }

  render() {
    return (
      <TextInput {...this.props} ref={dateTimePicker => this.dateTimePicker = dateTimePicker}/>
    )
  }
}

有没有办法“在其他东西满载之后需要一些东西?”。我错过了什么吗?

注 1:是的,我知道 jQuery + React = 不好,但是我喜欢这个组件,并且我正在将一个旧项目移植到使用这个库的 React,所以我认为将它作为一个 React 组件会很好。然而,我的主要目标是拥有一些看起来像 gijgo 并与 React 一起使用的日期时间选择器组件,因此我愿意接受建议。

注 2:我通过 npm ( npm install gijgo --save)使用 gijgo

更新 1

注意 3:我在 React JS 开发方面有点新,我不太确定我使用什么来进行捆绑,但我运行时运行的npm start脚本yarn startreact-scripts start. 此外,该错误还显示__webpack_require__

  779 | };
  780 | 
  781 | // Execute the module function
> 782 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  783 | 
  784 | // Flag the module as loaded
  785 | module.l = true;

更新 2

我尝试创建一个单独的文件来导入 jQuery 并在全局范围内设置它,所以我可以停止使用requireimport改用它。尽管如此,我仍然遇到同样的错误。

这是我的jQuery.js文件:

import jquery from 'jquery';
global.$= jquery;
global.jQuery = jquery;

这是我更新的导入:

(...)
import '../jQuery'
import 'gijgo/js/gijgo'
import 'gijgo/js/messages/messages.pt-br'
import 'gijgo/css/gijgo.css'
(...)

更新 3

当我尝试使用 gijgo from 时它不起作用<script>,它说datetimepicker无法识别。我一定是做错了什么,因为我很难理解如何将 jQuery 与 React 混合使用。我认为 gijgo 是一个很好的图书馆和一切。但是对于这种特殊情况,我实际上决定使用来自 material-ui/pickers 的 DateTimePicker

标签: javascriptjqueryreactjsdatetimepickerrequire

解决方案


推荐阅读