How to include external JavaScript library in reactjs

后端 未结 3 1890
不知归路
不知归路 2020-12-20 13:33

I would like to know how it\'s possible to include an external JavaScript library in a react project. For example, I would like to import the jspdf library : https://github.

3条回答
  •  天涯浪人
    2020-12-20 14:14

    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?

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

    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 (
          
    logo

    Welcome to React

    To get started, edit src/App.js and save to reload.

    ); } } export default App;

提交回复
热议问题