使用 typescript 将自定义断点添加到 Material ui

Yon*_*man 5 typescript reactjs material-ui

我知道在createMuiTheme()函数中您可以像这样更新断点的值。

const theme = createMuiTheme({
  breakpoints: {
    values: {
      xs: 0,
      sm: 600,
      md: 960,
      lg: 1280,
      xl: 1920,
    },
  },
})
Run Code Online (Sandbox Code Playgroud)

我还知道 Material UI(相对)最近更改了它,您可以为断点添加自定义值。

  breakpoints: {
    values: {
      tablet: 640,
      laptop: 1024,
      desktop: 1280,
    },
  },
});
Run Code Online (Sandbox Code Playgroud)

但是,我使用的是 Typescript,无法通过覆盖断点值来使其工作,如下所示:

declare module "@material-ui/core/styles/createBreakpoints"
{
  interface BreakpointOverrides
  {
    xs: false; // removes the `xs` breakpoint
    sm: false;
    md: false;
    lg: false;
    xl: false;
    tablet: true; // adds the `tablet` breakpoint
    laptop: true;
    desktop: true;
  }
}
Run Code Online (Sandbox Code Playgroud)

而是得到这个错误 Type '{ tablet: number; laptop: number; desktop: number; }' is not assignable to type 'BreakpointValues'. Object literal may only specify known properties, and 'tablet' does not exist in type 'BreakpointValues'.

不确定我做错了什么?任何帮助,将不胜感激。

小智 3

我正在使用打字稿和断点MaterialUI,我认为您需要导入和修改一些接口,如文档所述(https://material-ui.com/guides/typescript/#customization-of-theme)。例如,我有一个像这样的 Theme.tsx:

import { createMuiTheme } from '@material-ui/core/styles'
import {BreakpointOverrides} from "@material-ui/core/styles/createBreakpoints"

declare module "@material-ui/core/styles/createBreakpoints" {
  interface BreakpointOverrides {
    xs: false; // removes the `xs` breakpoint
    sm: false;
    md: false;
    lg: false;
    xl: false;
    tablet: true; // adds the `tablet` breakpoint
    laptop: true;
    desktop: true;
  }
}


declare module '@material-ui/core/styles/createMuiTheme' {
  interface Theme {
    appDrawer: {
      width: React.CSSProperties['width']
      breakpoint: BreakpointOverrides
    }
  }
  // allow configuration using `createMuiTheme`
  interface ThemeOptions {
    appDrawer?: {
      width?: React.CSSProperties['width']
      breakpoint?: BreakpointOverrides
    }
  }
}
export const theme = createMuiTheme({
  breakpoints: {
    values: {
      tablet: 400,
      laptop: 900,
      desktop: 1200
    }
  },})
Run Code Online (Sandbox Code Playgroud)