我想使用typescript从Material-UI扩展Button组件的道具,以便能够将额外的道具传递给它的子项.
import { NavLink } from 'react-router-dom';
import { Button } from 'material-ui';
<Button
component={NavLink}
// NavLink props that needs to be added to typescript declarations
activeClassName={classes.activeButton}
exact={true}
to={to}
>
{title}
</Button>
我试图在./app/types/material_ui.d.ts中添加以下声明:
declare module 'material-ui' {
interface Button {
activeClassName?: any;
exact?: boolean;
to?: string;
}
}
抛出错误“TS2693:’Button’只引用一个类型,但在这里被用作值.”
我也试过这个宣言:
import * as React from 'react';
import { PropTypes, StyledComponent } from 'material-ui';
import { ButtonBaseProps } from 'material-ui/ButtonBase';
declare module 'material-ui' {
export interface ButtonProps extends ButtonBaseProps {
color?: PropTypes.Color | 'contrast';
component?: React.ReactNode;
dense?: boolean;
disabled?: boolean;
disableFocusRipple?: boolean;
disableRipple?: boolean;
fab?: boolean;
href?: string;
raised?: boolean;
type?: string;
activeClassName?: any;
exact?: boolean;
to?: string;
}
export class Button extends StyledComponent<ButtonProps> { }
}
其中引发错误“TS2323:无法重新声明导出的变量’按钮’”.
我的tsconfig.json看起来像这样:
{
"compilerOptions": {
...
"paths": {
"history": ["./node_modules/@types/history/index"],
"redux": ["./node_modules/@types/redux/index"],
"react": ["./node_modules/@types/react/index"],
"*": ["./app/types/*", "*"]
},
},
...
}
最后来自Material-UI的原始类型定义:
import * as React from 'react';
import { StyledComponent, PropTypes } from '..';
import { ButtonBaseProps } from '../ButtonBase';
export interface ButtonProps extends ButtonBaseProps {
color?: PropTypes.Color | 'contrast';
component?: React.ReactNode;
dense?: boolean;
disabled?: boolean;
disableFocusRipple?: boolean;
disableRipple?: boolean;
fab?: boolean;
href?: string;
raised?: boolean;
type?: string;
}
export default class Button extends StyledComponent<ButtonProps> {}
我正在使用material-ui 1.0.0-beta.8 with react 15.6.1,react-router-dom 4.2.2和typescript 2.5.2.
最佳答案 以下代码适用于我
import { Button, StyledComponent } from 'material-ui';
import { ButtonProps } from 'material-ui/Button';
declare module 'material-ui' {
export interface MyProps {
exact?: boolean;
to?: string;
}
export class Button extends StyledComponent<ButtonProps & MyProps> {
}
}
“我没有问题”TS2693:’Button’只引用一个类型,但在这里被用作一个值.我也在使用Typescript 2.5.2