如何使用TypeScript扩展Material-UI组件的道具? [英] How to extend props for Material-UI components using Typescript?
本文介绍了如何使用TypeScript扩展Material-UI组件的道具?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望使用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/type/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:无法重新声明导出的变量‘Button’"。
我的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与REACTION 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' only refers to a type, but is being used as a value here.
没有问题,我也在使用TypeScript 2.5.2
这篇关于如何使用TypeScript扩展Material-UI组件的道具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文