我如何为现有组件定义打字稿@type

时间:2018-10-03 09:09:21

标签: reactjs typescript

我在npm之前得到了jqwidgets-framework:

npm install jqwidgets-framework -D

该框架通过javascript实现了很多react组件。 例如:

... 
export default class JqxCheckBox extends React.Component {
        componentDidMount() {
            let options = this.manageAttributes();
            this.createComponent(options);
        }; 
...

但是我的项目写的是打字稿,所以我无法将此框架集成到我的项目中。

我正在尝试添加新文件 jqw.d.ts

/// <reference path="../../node_modules/jqwidgets-framework/jqwidgets-ts/jqwidgets.d.ts" />

import * as React from "react";
import * as CSS from 'csstype';

interface IJqxCheckBoxProps extends jqwidgets.CheckBoxOptions {
    style?: CSS.Properties<string | number>;
    value: string;
    //on?: (name?: string, callback?: Function ) => void;
    // render?: ()=>void;
}
declare class JqxCheckBox extends React.Component<IJqxCheckBoxProps, any> { }

export default JqxCheckBox;

并在react中使用此组件:

/// <reference path="jqw.d.ts"/>

import '../css/site.css';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
//import 'jqwidgets-framework/jqwidgets-react/react_jqxdatatable';
import 'jqwidgets-framework/jqwidgets-react/react_jqxcheckbox';
import * as CSS from 'csstype';
.......
render() {
  let chexboxCSS: CSS.Properties<string | number> = { marginLeft: 10, float: 'left' };
  let checkboxParentCSS: CSS.Properties<string | number> = { float: 'left', width: 400, marginTop: 10 };
  return (
      <div style={{ fontFamily: 'Verdana Arial', fontSize: 12, width: 400 }}>
          <div style={{ float: 'left', width: 400 }}>
              <h3 style={{ marginLeft: 15 }}>Categories</h3>
              <JqxCheckBox style={chexboxCSS} value='Entertainment'
                  width={120} height={25}
              />
              <JqxCheckBox style={chexboxCSS} value='Computers'
                  width={120} height={25} checked={true}
              />
              <JqxCheckBox style={chexboxCSS} value='Sports'
                  width={120} height={25}
              />
.......

但是它不起作用

如何定义现有组件的类型?

1 个答案:

答案 0 :(得分:0)

使用module declaration将类型声明与原始jqwidgets-framework/jqwidgets-react/react_jqxcheckbox模块关联:

/// <reference path="node_modules/jqwidgets-framework/jqwidgets-ts/jqwidgets.d.ts" />

declare module "jqwidgets-framework/jqwidgets-react/react_jqxcheckbox" {
    import * as React from "react";
    import * as CSS from 'csstype';

    interface IJqxCheckBoxProps extends jqwidgets.CheckBoxOptions {
        style?: CSS.Properties<string | number>;
        value: string;
        //on?: (name?: string, callback?: Function ) => void;
        // render?: ()=>void;
    }
    class JqxCheckBox extends React.Component<IJqxCheckBoxProps, any> { }

    export default JqxCheckBox;
}