【问题标题】:Using withStyles of material-ui v1 in a nested manner以嵌套方式使用material-ui v1的withStyles
【发布时间】:2018-05-18 15:11:30
【问题描述】:

所以我有这个组件,我正在尝试以反应方式编写。每个主要容器都作为 React 类组件分开。 现在我知道如何将 withStyles 与一个组件一起使用: 导出默认 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。

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    您的问题与 withStyles 无关,而与您组织组件和导出的方式有关。

    解决方案 1:

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

    export default withStyles(styles)(MyComponent);
    

    在您在帖子中提到的每个文件中。

    解决方案 2:

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

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

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

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

    【讨论】:

    • 是的,我知道,但问题是一个主要组件包含 8,9 个子组件或类,从而导致大量文件。那很好吗? @klugjo
    【解决方案2】:

    为了自己处理这个问题,我偶然发现了一个有用的工具,可以通过 Material-UI 使用类似于 Styled-Components™ 的 API。

    Gist example

    导入后为:

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

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

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

    与默认的withStyles() API 的一个区别是,此工具将样式应用于root 类,因此您不能为一个组件嵌套多个样式样式(可能可以轻松升级以允许这样做)。

    但是对于简单样式的复用性来说真的很方便,不需要创建太多文件。

    Credit to the (probable) author

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 1970-01-01
      • 2019-11-21
      • 2018-11-20
      • 1970-01-01
      • 2019-07-10
      • 2020-06-21
      • 2019-06-14
      • 2019-09-21
      相关资源
      最近更新 更多