網站搜尋

reactjs - Material UI Typescript - createStyles 問題


我有以下測試程式碼(依照 Material UI TypeScript 文件中的指南)

import * as React from 'react';

import { Theme } from '@material-ui/core/styles/createMuiTheme';
import { WithStyles } from '@material-ui/core';
import { createStyles } from '@material-ui/core/styles';
import Drawer from '@material-ui/core/Drawer';

const drawerWidth = 240;

const styles = (theme: Theme) => createStyles({
  root: {
    flexGrow: 1,
    height: 430,
    zIndex: 1,
    overflow: 'hidden',
    position: 'relative',
    display: 'flex',
  },
  appBar: {
    zIndex: theme.zIndex.drawer + 1,
  },
  drawerPaper: {
    position: 'relative',
    width: drawerWidth,
  },
  content: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.default,
    padding: theme.spacing.unit * 3,
    minWidth: 0,
  },
  toolbar: theme.mixins.toolbar,
});

interface Props extends WithStyles<typeof styles> {}
interface State {}

export class Sidebar extends React.Component<Props, State> {
  render() {
    const { classes } = this.props;
    return (
      <Drawer
        style={{position: 'relative', width: drawerWidth}}
        variant='permanent'
        classes={{
          paper: classes.drawerPaper,
        }}
      >
        <div className={classes.toolbar} />
      </Drawer>
    );
  }
}

export default Sidebar;

現在,如果我嘗試在其他地方使用這個組件,方法是:

import * as React from 'react';

import Grid from '@material-ui/core/Grid';

import Sidebar from './Sidebar';


export class Main extends React.Component {
  public render() {
    return (
      <Grid container>
        <Grid container item xs={12}>
          <Sidebar />
        </Grid>
      </Grid>
    );
  }
}

export default Main;

我遇到的錯誤是,在 Main 元件中缺少 classes,而在 SideBar 元件中則出現 cannot read property drawerPaper of undefined。我以為 extend WithStyles<typeof styles> 可以解決這個問題,但在嘗試匯入並使用 SideBar 元件時仍然沒有幫助。我對 Material UI 主題設定經驗很少,所以任何指導都將非常感激。

答案#1

你還沒有將樣式附加到元件。你的程式碼中沒有將你創建的樣式與其餘程式碼連接起來。

要做到這一點,你需要使用高階組件 withStyles。不要使用 export default Sidebar;,只需使用 export default withStyles(styles)(Sidebar);