我有一个使用标准黑暗主题的主题提供者。我希望能够从我自己的自定义组件中访问此主题的详细信息,但我无法弄清楚如何完成。在下面的示例中,struct Types : OptionSet, Codable
未定义
this.props.theme
答案 0 :(得分:3)
您需要使用材料-ui提供的HOC(高阶组件)(注意我使用的是测试版,YMMV)。
示例:
<强> LeftNavigation.jsx 强>
import React from 'react';
import PropTypes from 'prop-types';
import Hidden from 'material-ui/Hidden';
import Drawer from 'material-ui/Drawer';
import List from 'material-ui/List';
import Divider from 'material-ui/Divider';
import { withStyles } from 'material-ui/styles';
import { MailFolderListItems, OtherMailFolderListItems } from '../../../components/tileData';
const styles = theme => ({
docked: {
height: '100%',
},
drawerPaper: {
width: 250,
height: '100%',
[theme.breakpoints.up('md')]: {
width: theme.drawerWidth,
position: 'relative',
height: '100%',
},
},
drawerHeader: theme.mixins.toolbar,
});
class LeftNavigation extends React.Component {
render() {
const { classes, theme } = this.props;
const drawer = (
<div>
<div className={classes.drawerHeader} />
<Divider />
<List><MailFolderListItems toggle={this.props.handleDrawerToggle} /></List>
<Divider />
<List><OtherMailFolderListItems toggle={this.props.handleDrawerToggle} /></List>
</div>
);
return [
<Hidden mdUp key="mobile">
<Drawer
type="temporary"
anchor={theme.direction === 'rtl' ? 'right' : 'left'}
open={this.props.mobileOpen}
classes={{ paper: classes.drawerPaper }}
onRequestClose={this.props.handleDrawerToggle}
ModalProps={{ keepMounted: true /* Better open performance on mobile. */ }}
>
{drawer}
</Drawer>
</Hidden>,
<Hidden mdDown implementation="css" key="desktop">
<Drawer
type="permanent"
open
classes={{
docked: classes.docked,
paper: classes.drawerPaper,
}}
>
{drawer}
</Drawer>
</Hidden>,
];
}
}
LeftNavigation.propTypes = {
classes: PropTypes.object.isRequired,
theme: PropTypes.object.isRequired,
mobileOpen: PropTypes.bool.isRequired,
handleDrawerToggle: PropTypes.func.isRequired
};
export default withStyles(styles, { withTheme: true })(LeftNavigation);
const styles = theme => ({...})
是您定义样式的地方。
export default withStyles(styles, { withTheme: true })(LeftNavigation);
显示高阶组件的用法,将样式/主题向下传递给组件。
我使用withTheme: true
,这样不仅可以使用我的样式,还可以传递主题。
因此,对于您的代码,我会执行以下操作:
import { withStyles } from 'material-ui/styles';
const styles = theme => ({
root: {
height: '100%'
}
})
class App extends Component {
render() {
const {classes} = this.props;
return (
<div className="App">
<MainMenu/>
<div className={classes.root}>
<Grid container spacing={8}>
<Grid item xs>
<Chart theme={this.props.theme}/>
</Grid>
</Grid>
</div>
</div>
);
}
}
export default withStyles(styles, { withTheme: true})(App);
答案 1 :(得分:1)
您还可以使用useTheme挂钩!
import { useTheme } from '@material-ui/styles';
function DeepChild() {
const theme = useTheme();
return <span>{`spacing ${theme.spacing}`}</span>;
}
https://material-ui.com/styles/advanced/#accessing-the-theme-in-a-component
答案 2 :(得分:0)
对于使用Typesctipt和类组件的人,您还需要添加:
export interface MyComponentNameProps extends WithStyles<typeof styles, true> {
// your props here...
theme: Theme
}