复写class接口方式, 这里用antd来举例子
/types/global.ts
import * as PropTypes from 'prop-types';
import { Table } from 'antd';
declare type TableSize = 'default' | 'middle' | 'small';
export declare class TableT<T> extends Table<T> {
static propTypes: {
dataSource: PropTypes.Requireable<any[]>;
columns: PropTypes.Requireable<any[]>;
prefixCls: PropTypes.Requireable<string>;
useFixedHeader: PropTypes.Requireable<boolean>;
rowSelection: PropTypes.Requireable<object>;
className: PropTypes.Requireable<string>;
size: PropTypes.Requireable<TableSize>;
loading: PropTypes.Requireable<boolean | object>;
bordered: PropTypes.Requireable<boolean>;
onChange: PropTypes.Requireable<(...args: any[]) => any>;
locale: PropTypes.Requireable<object>;
dropdownPrefixCls: PropTypes.Requireable<string>;
sortDirections: PropTypes.Requireable<any[]>;
batchButtons: any;
};
}
/xxx/xxx.tsx
import { TableT } from 'types/global.ts';
/// <reference path = "types/global.ts" />
class demo extends React.Component {
render(){
return(<Table ... />);
}
}
如果你的eslint或tslint报错了,告诉你某某某组件没有某个参数或者方法
// 使用接口基础的方式,讲属性或方法添加上
interface HTMLElementDom extends HTMLElement {
select?: () => void;
value?: string;
}
// 使用时
(dom as HTMLElementDom).value
(dom as HTMLElementDom).select();
自定义属性
// 新版本的,建议使用此种语法
declare module 'react' {
interface HTMLAttributes<T> extends DOMAttributes<T> {
block?: string
element?: string
modifiers?: Modifiers // <-- custom interface
}
}
// 旧版本的
declare namespace React {
interface HTMLProps<T> extends HTMLAttributes, ClassAttributes<T> {
}
}
// 一个例子
import * as React from 'react';
declare module 'react' {
interface HTMLProps<T> {
block?:string;
element?:string;
modifiers?:string;
}
}
export const Foo = () => {
return (
<div block="123" element="456">
</div>
)
};
// 定义公共
import * as React from 'react';
import './react_augmented';
传递Event
public selectFn: (event: React.MouseEvent<HTMLSpanElement, MouseEvent>) => void = (e) => {
// 这里要强制类型转换才可以使用getAttribute方法
const target = (e.target as HTMLElement);
console.log('selectFn', target.getAttribute('uid'));
}
<Component selectFn={this.selectFn} />
interface Props {
selectFn(event: React.MouseEvent<HTMLSpanElement, MouseEvent>): void;
}