材质UI打字稿-createStyles问题

Joh*_*n B 3 typescript reactjs material-ui

我有以下测试代码(按照Material UI打字稿文档中的指南进行操作)

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;
Run Code Online (Sandbox Code Playgroud)

现在,如果我尝试通过以下方式在其他地方使用此组件:

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;
Run Code Online (Sandbox Code Playgroud)

我收到了classesMain组件和cannot read property drawerPaper of undefinedSideBar组件内缺少的错误。我extend WithStyles<typeof styles>以为可以解决该问题,但是在尝试导入和使用该SideBar组件时仍然无济于事。我对Material UI主题的经验很少,因此非常感谢您提供任何指导。

nib*_*iba 5

您尚未将样式附加到组件。在您创建的样式与其余代码之间,代码之间没有任何联系。

为此,您需要使用HOC withStyles。而不export default Sidebar;只是做export default withStyles(styles)(Sidebar);