2017-09-05 70 views
1

我正在使用TypeScript(2.4.2)進行第一次入侵React(15.6.1),並試圖創建一個代表JSON的組件可拖動的字段。這裏是我的組件代碼:如何使用TypeScript將拖動事件處理程序附加到React組件

import * as React from "react"; 

interface JsonFieldProps { 
    name: string; 
    type: string; 
    indent: number; 
} 

export class JsonField extends React.Component<JsonFieldProps, undefined> { 
    marginStyle = { 
     'text-indent': `${this.props.indent * 15}px` 
    }; 

    render() { 
     return <div draggable={true} onDragStart={handleDrag} style={this.marginStyle}>{this.props.name}: {this.props.type},</div>; 
    } 
} 

function handleDrag(ev: DragEvent): void { 
    let id = (ev.target as HTMLDivElement).id; 
    ev.dataTransfer.setData("text/plain", id); 
} 

當我嘗試編譯它(使用的WebPack),我收到以下錯誤:

ERROR in [at-loader] ./src/components/JsonField.tsx:15:21 
    TS2322: Type '{ draggable: true; onDragStart: (ev: DragEvent) => void; 
    style: { 'text-indent': string; }; child...' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'. 
    Type '{ draggable: true; onDragStart: (ev: DragEvent) => void; style: { 'text-indent': string; }; child...' is not assignable to type 'HTMLAttributes<HTMLDivElement>'. 
    Types of property 'onDragStart' are incompatible. 
     Type '(ev: DragEvent) => void' is not assignable to type 'EventHandler<DragEvent<HTMLDivElement>>'. 
     Types of parameters 'ev' and 'event' are incompatible. 
      Type 'DragEvent<HTMLDivElement>' is not assignable to type 'DragEvent'. 
      Property 'initDragEvent' is missing in type 'DragEvent<HTMLDivElement>'. 

我不知道如果我使用了錯誤的事件類型,但我似乎無法找到任何關於哪一個是正確的信息,如果它是錯誤的。如您使用的反應,而不是純HTML的text-indenttextIndent

export class JsonField extends React.Component<JsonFieldProps, undefined> 
{ 
    private marginStyle = { 
     textIndent: `${this.props.indent * 15}px` 
    }; 

    public render() 
    { 
     return (
      <div 
       draggable={true} 
       onDragStart={handleDrag} 
       style={this.marginStyle}> 
       {this.props.name}: {this.props.type} 
      </div>); 
    } 
} 

function handleDrag(ev: React.DragEvent<HTMLDivElement>): void 
{ 
    const id = (ev.target as HTMLDivElement).id; 
    ev.dataTransfer.setData("text/plain", id); 
} 

還要注意的變化:

+0

Facebook使[流](https://flow.org/)可能與React更好地發揮,請參閱[也是](https://flow.org/en/docs/react/)。 –

回答

1

必須使用React.DragEvent接口,而不是一般的DOM DragEvent的。請記住,你主要使用虛擬DOM,而不是真正的虛擬DOM - 因此所有這些變化。

作爲一個便箋,我會建議你在課堂中保持事件處理程序,而不是在它之外。這樣你就可以訪問類的實例屬性和方法。

+0

謝謝,這個伎倆。一個需要注意的是IntelliJ不能識別導出。 TS2694:命名空間'React'沒有導出成員'DragEvent'。'任何想法如何解決? – Jared

+0

不幸的是我沒有使用IntelliJ的經驗。對此的常見原因是缺少或過時的打字稿定義的反應。嘗試安裝他們的最新版本。你也可以檢查這個線程:https://intellij-support.jetbrains.com/hc/en-us/community/posts/208367645-TypeScript-types-node – Amid

相關問題