我正在使用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-indent
到textIndent
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);
}
還要注意的變化:
Facebook使[流](https://flow.org/)可能與React更好地發揮,請參閱[也是](https://flow.org/en/docs/react/)。 –