所以我有这个组件,我正在尝试以 react 方式编写。其中每个主要容器都被分隔为 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 ?;
现在的问号是还应该做什么才能将样式作为 prop 通过 AtmanPage 传递给 AtmanAppBar。
最佳答案
您的问题与 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';
关于javascript - 嵌套使用material-ui v1的withStyles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47645467/