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: エクスポートされた変数 '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> {}
私は、react 15.6.1、react-router-dom 4.2.2、typescript 2.5.2 を搭載した material-ui 1.0.0-beta.8 を使用しています。
ベストアンサー1
少し遅くなりましたが、別の解決策があります。MUIドキュメントも参照してください。コンポーネントプロパティの使用次のボタンは Link コンポーネントを使用します。また、Link の特定のプロパティとそのタイプも使用します。また、独自のプロパティも追加します。
import React from 'react'
import MuiButton, {ButtonProps} from '@material-ui/core/Button'
interface ButtonOptions {
// your custom options with their types
}
const Button = <C extends React.ElementType>(props: ButtonProps<C, {component?: C}> & ButtonOptions ) => {
return <MuiButton {...props}>{props.children}</MuiButton>
}
export default Button
// use like this:
import {Link} from 'react-router-dom'
<Button component={Link} to={'/somelocation'}>