首页 文章

以嵌套方式使用withStyles of material-ui v1

提问于
浏览
0

所以我有这个组件,我试图以反应的方式写 . 其中每个主要容器都被分隔为React类组件 . 现在我知道如何将withStyles与一个组件一起使用:export default withStyles(styles)(MyComponent);

但是当你有两个以上的组件时,你如何使用withStyles . 这是代码:

class AtmanPage extends Component {
  render() {
    return (
      <AtmanAppBar />
    );
  }
}


class AtmanAppBar extends Component {
  render() {
    return (
      <div className= {this.props.classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton className= {this.props.classes.menubutton} color="contrast" aria-label="Menu">
            <MenuIcon />
          </IconButton>
          <Typography type="title" color="inherit" className={this.props.classes.flex}>
            Title
          </Typography>
          <Button color="contrast">Login</Button>
        </Toolbar>
      </AppBar>
          </div>
    );
  }
}

const styles = theme => ({
  root: {
    marginTop: theme.spacing.unit * 3,
    width: '100%',
  },
  flex: {
    flex: 1,
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20,
  },
});

export default withStyles(styles) AtmanPage ?;

现在问号是关于通过AtmanPage将样式作为道具传递给AtmanAppBar应该做些什么 .

2 回答

  • -1

    为了自己处理这个shizzle,我遇到了一个有用的工具,通过Material-UI使用类似Styled-Components™的API .

    Gist example

    导入后:

    import styled from '../utils/styled';
    

    您可以在一个文件中创建许多Styled-Components-lookalike:

    const List = styled('ul')(theme => ({
      padding: theme.spacing.unit,
      margin: 0,
    }));
    

    与默认 withStyles() API的一个区别是,此util将样式应用于 root 类,因此您无法为一个组件嵌套多个样式样式(可能很容易升级以允许该tbh) .

    但是对于简单的样式可重用性而言,它非常方便,而无需创建太多文件 .

    Credit to the (probable) author

  • 0

    您的问题与 withStyles 无关,但与组织组件和导出的方式无关 .

    Solution 1:

    您可以将每个组件放在单独的文件中并使用

    export default withStyles(styles)(MyComponent);
    

    在你的帖子中提到的每个文件中 .

    Solution 2:

    如果您希望将它们保存在同一个文件中,则可以对两个类进行简单导出:

    export const StyledAtmanAppBar = withStyles(styles)(AtmanAppBar);
    export const StylesAtmanPage = withStyles(styles)(AtmanPage);
    

    然后你需要在另一个文件中导入它们:

    import {StyledAtmanAppBar, StylesAtmanPage} from './path/to/your/file';
    

相关问题