如何在 reactjs 中包含外部 javascript 库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36066508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:35:51  来源:igfitidea点击:

How to include external javascript library in reactjs

javascriptreactjsjspdf

提问by FLCcrakers

I would like to know how it's possible to include an external javascript library in a react project. For exemple, I?would like to import the jspdf library :?https://github.com/MrRio/jsPDF/blob/master/jspdf.jsand use it in my reactjs app.

我想知道如何在 React 项目中包含外部 javascript 库。例如,我想导入 jspdf 库 :? https://github.com/MrRio/jsPDF/blob/master/jspdf.js并在我的 reactjs 应用程序中使用它。

So far I?tried to use require like this :?

到目前为止,我尝试像这样使用 require :?

let React = require('react');
let { Spacing, Typography } = Styles;
let DoughnutChart = require("react-chartjs").Doughnut;
let Chart = require('react-google-charts').Chart;
let { StylePropable, StyleResizable } = Mixins;
let EditableDiv = require('../EditableDiv.jsx');
//some other library
//the library that matter for me
var pdfConverter = require('../utils/jspdf.source.js');

//then I?have my classical react code which works and a function to generate ad pdf
_generatePdf: function(){
    console.log('Genrating pdf');
    var doc = new pdfConverter.jsPDF('p','pt');
    var img = new Image();
}

I have the following error :?TypeError: pdfConverter.jsPDF is not a function.

我有以下错误:?TypeError: pdfConverter.jsPDF is not a function

To make it work, I made something ugly, I?copy the source of jspdf-source.js into my react.jsx file and just call jsPDF instead of pdfConverter.jsPDF. It's definitly no the right way, but can't succed to import and use the library.

为了使它工作,我做了一些丑陋的事情,我将 jspdf-source.js 的源代码复制到我的 react.jsx 文件中,然后调用 jsPDF 而不是 pdfConverter.jsPDF。这绝对不是正确的方法,但无法成功导入和使用该库。

Can you tell me what I'm doing wrong and how I?can correct this? Thank you

你能告诉我我做错了什么以及如何纠正吗?谢谢

-EDIT-

-编辑-

When I?was using my ugly solution (copying the source into my file) I just had to do the following :

当我使用我丑陋的解决方案(将源文件复制到我的文件中)时,我只需要执行以下操作:

var doc = new jsPDF('p','pt);

And it was working perfectly, expect that I?had a very big file

它运行良好,希望我有一个非常大的文件

After the suggested solution from @dannyjolie bellow, I've imported jspdf directly from the npm package, but I'm still not able to use the library. I tried the following code wich lead to an error:

在@dannyjolie bellow 提出建议的解决方案之后,我直接从 npm 包中导入了 jspdf,但我仍然无法使用该库。我尝试了以下代码导致错误:

var pdfConverter = require('jspdf');
var converter = new pdfConverter();
var doc = converter.jsPDF('p', 'pt');

TypeError: pdfConverter is not a constructorMeaning that I?have to import the jsPDF coming from the package, not only jspdf ?

TypeError: pdfConverter is not a constructor 这意味着我必须导入来自包的 jsPDF ,而不仅仅是 jspdf ?

Then I?try

那我试试

let pdfConverter = require('jspdf');
var converter = pdfConverter.jsPDF;
var doc = new converter('p', 'pt');

ReferenceError: jsPDF is not defined

参考错误:未定义 jsPDF

TypeError: converter is not a constructor

类型错误:转换器不是构造函数

Ok obviously, I'm not importing the right thing or not the right way. What I'm doing wrong ?

好吧,显然,我没有导入正确的东西或不正确的方式。我做错了什么?

采纳答案by dannyjolie

First of all, don't use the source file. Just npm install jspdf --savelike any other package, and import it with var pdfConverter = require('jspdf');

首先,不要使用源文件。只是npm install jspdf --save像任何其他包,并用它进口var pdfConverter = require('jspdf');

Secondly, you're missing a () in this line var doc = new pdfConverter.jsPDF('p','pt');

其次,您在这一行中缺少一个 () var doc = new pdfConverter.jsPDF('p','pt');

Do something like this:

做这样的事情:

var converter = new pdfConverter();
var doc = converter.jsPDF('p', 'pt');

回答by Jason Kao

If you include the external js file link in your /public/index.html, you can use the external library with the windowprefix.

如果在 .js 文件中包含外部 js 文件链接/public/index.html,则可以使用带有window前缀的外部库。

Take JQuery as an example. Put the following line in your /public/index.html:

以 JQuery 为例。将以下行放入您的/public/index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Use it in your project like so:

在您的项目中使用它,如下所示:

window.$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});

回答by James Young

I know this is old, but I thought it would be helpful if someone posted a full working sample. It took me a while to figure this out, using this other post as a starting point:

我知道这是旧的,但我认为如果有人发布完整的工作样本会有所帮助。我花了一段时间才弄清楚这一点,使用另一篇文章作为起点:

How to make PDF from React?

如何从 React 制作 PDF?

Assuming you are using create-react-app, overwrite your App.js with the following below...

假设您正在使用 create-react-app,请使用以下内容覆盖您的 App.js...

import React, { Component } from 'react';
import pdfConverter from 'jspdf';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
    this.toDataUrl = this.toDataUrl.bind(this);
  }

  toDataUrl(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
      var reader = new FileReader();
      reader.onloadend = function() {
        callback(reader.result);
      }
      reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
  }

  onClick() {
      var doc = new pdfConverter('p','pt','letter');
      //console.log(doc.getFontList() );
      this.toDataUrl('background.jpg', function(base64Img) {
        var imgData = base64Img;
        console.log(imgData);
        console.log('Adding to doc.');
        doc.addImage(imgData, 'JPEG', 0, 0, 612, 792);
        console.log('Image added.');
        doc.setFont('Times', 'Roman');
        doc.setFontSize(22);
        doc.text(20, 50, 'Park Entry Ticket');
        doc.setFontSize(16);
        doc.text(20, 80, 'Address1: ' );
        doc.text(20, 100, 'Address2: ' );
        doc.text(20, 120, 'Entry Date & time: ');
        doc.text(20, 140, 'Expiry date & time: ' );
        console.log('About to save');
        doc.save("test.pdf");
      });
  }

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
            <input type='button'
        onClick={this.onClick} value="Print"/>
        </p>
      </div>
    );
  }
}

export default App;