2017-05-29 74 views
1

我正在嘗試導入節點模塊React-Signature-Pad。該index.js文件看起來像這樣:導入節點模塊導出默認類導致'模塊'不是'構造函數'

import PropTypes from 'prop-types' 
import React, { Component } from 'react' 
import trimCanvas from 'trim-canvas' 

import Bezier from './bezier.js' 
import Point from './point.js' 

export default class SignatureCanvas extends Component { 
    static propTypes = { 
    velocityFilterWeight: PropTypes.number, 
    minWidth: PropTypes.number, 
    maxWidth: PropTypes.number, 
    dotSize: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), 
    penColor: PropTypes.string, 
    onEnd: PropTypes.func, 
    onBegin: PropTypes.func, 
    canvasProps: PropTypes.object 
    } 

    static defaultProps = { 
    velocityFilterWeight: 0.7, 
    minWidth: 0.5, 
    maxWidth: 2.5, 
    dotSize:() => { 
     return (this.props.minWidth + this.props.maxWidth)/2 
    }, 
    penColor: 'black', 
    backgroundColor: 'rgba(0,0,0,0)', 
    onEnd:() => {}, 
    onBegin:() => {} 
    } 

    componentDidMount() { 
    this._ctx = this._canvas.getContext("2d"); 
    //..... 

我想用這樣的:import * as SignatureCanvas from 'react-signature-canvas'

但是隨後SignatureCanvas evaulates將物體與「默認」的單一屬性。所以當我使用我得到一個錯誤,因爲SignatureCanvas實際上不是一個構造函數。

我已經能夠得到這個工作的唯一方法是將其導入這樣的:

declare var require: any; 
var SignatureCanvas = require('react-signature-canvas').default; 

似乎這也不對。哪個是正確的導入方式?

我使用WebPack2捆綁網站,如果它很重要。

回答

0

您必須導入等,作爲模塊有一個默認的出口成員:

import SignatureCanvas from 'react-signature-canvas' 

默認的導出是一個簡單的命名爲出口名稱爲default。所以,你甚至可以這樣做:

import { default as SignatureCanvas } from 'react-signature-canvas' 

或者:

import * as SignatureCanvas from 'react-signature-canvas' 

//... and use the `SignatureCanvas` class by accessing the `default property` 
new SignatureCanvas.default() 

見關於違約出口文檔:https://www.typescriptlang.org/docs/handbook/modules.html#default-exports

+0

謝謝。我無法獲得這種語法在TypeScript中編譯。我創建了一個客戶.d.ts文件,我在導入行上發現錯誤,指出沒有默認導出。但是我發現在聲明文件中更改導出= SignatureCanvas以導出默認SignatureCanvas與您的答案一起工作。謝謝。 - sheamus剛剛編輯 – sheamus

1

導入此模塊的方式 - 有工作作爲一類 - 是:

import SignatureCanvas from 'react-signature-canvas'; 

var x = new SignatureCanvas(...); 

import * as xxx from 'xxx'語法的工作原理與您發現的一樣:def模塊xxx的輸出僞影設置爲xxx.default。在你的情況下,你將不得不:

import * as SignatureCanvas from 'react-signature-canvas'; 

var x = new SignatureCanvas.default(...); // now x is the same as above