材质UI打字稿-createStyles问题

时间:2018-06-21 14:52:58

标签: reactjs typescript 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;

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

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;

在主组件中缺少classes,在SideBar组件中缺少cannot read property drawerPaper of undefined的错误。我认为extend WithStyles<typeof styles>将解决该问题,但是在尝试导入和使用SideBar组件时仍然没有帮助。我对Material UI主题的经验很少,因此非常感谢任何指导。

1 个答案:

答案 0 :(得分:3)

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

要执行此操作,您需要使用HOC #include <bits/stdc++.h> using namespace std; class User{ public: int URI; User(int a){ URI = a; } }; class Group { public: static vector<User> members; void remove(User a) { for (int i = 0; i < members.size();){ if (a.URI == (*(members.begin()+i)).URI) members.erase((members.begin() + i)); else i++; } } Group(User a, User b, User c){ members.push_back(a); members.push_back(b); members.push_back(c); } }; vector<User> Group::members; int main() { User a(1), b(2), c(3); Group obj(a, b, c); obj.remove(a); return 0; } 。不用withStyles,而要做export default Sidebar;