【问题标题】:Material UI Typescript - createStyles IssueMaterial UI Typescript - createStyles 问题
【发布时间】:2018-06-21 14:52:58
【问题描述】:

我有以下测试代码(按照 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;

我收到错误消息,即 Main 组件中缺少 classes,而 SideBar 组件中缺少 cannot read property drawerPaper of undefined。我认为extend WithStyles&lt;typeof styles&gt; 可以解决这个问题,但在尝试导入和使用SideBar 组件时它仍然无济于事。我对 Material UI 主题的经验很少,因此非常感谢任何指导。

【问题讨论】:

    标签: reactjs typescript material-ui


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-05-24
      • 2021-04-01
      • 2020-08-13
      • 2019-09-20
      • 2018-12-02
      • 2017-08-19
      • 2022-11-10
      • 2021-11-14
      • 1970-01-01
      相关资源
      最近更新 更多