问题
I try to create AppBar clipped to the page top and hovering over other Drawer with React Hooks and Material Ui using class name. All as described in: https://material-ui.com/demos/drawers/#clipped-under-the-app-bar
So we have
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
height: '100%',
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
appBar: {
zIndex: theme.zIndex.drawer + 1,
},
menuButton: {
marginRight: 20,
[theme.breakpoints.up('md')]: {
display: 'none',
},
},
}));
And reder:
<div className={classes.root}>
<CssBaseline/>
<LoadingResults showLoading={showLoadingSpinner}/>
<AppBar position="fixed" className={classes.appBar} >
...
</AppBar>
....
Problem is that the style applied with className is added last of the element so its not overriding the orignal style:
class="MuiPaper-root-12 MuiPaper-elevation4-18 MuiAppBar-root-3 MuiAppBar-positionFixed-4 MuiAppBar-colorPrimary-10 mui-fixed Hook-appBar-1b6f20g"
I know I can use inline styles but wonder to know if I can override styles using classNames with hooks as it was with "legacy" component approach ?
Here is sandbox: https://codesandbox.io/s/w7njqorzy7?fontsize=14
What happens is that in sandbox the code works ok (appbar over lefthand side container)
But when the same project is downloaded and compiled it's not ok:
Looking at the debuger the styles are inline. In the sandbox hooks are at the bottom:
In the browser when app is run via "run start" its on top:
So this is the difference, but why and how to fix this ?
回答1:
Turned out that my bootstrap.js with new styles install was in wrong place.
import { install } from '@material-ui/styles';
install();
Should be executed before any material ui component is imported.
回答2:
https://material-ui.com/ru/styles/advanced/#makestyles
const useStyles = makeStyles({
root: {}, // a style rule
label: {}, // a nested style rule
});
function Nested(props) {
const classes = useStyles(props);
return (
<button className={classes.root}>
<span className={classes.label}> // 'jss2 my-label'
nested
</span>
</button>
);
}
function Parent() {
return <Nested classes={{ label: 'my-label' }} />
}
回答3:
You can override material-ui styles with classes
props instead of classNames
.
For example
<AppBar position="fixed" classes={{root: classes.appBar}}>
Here I have used root
key to override, there are many other keys with which you can play around.
Every Material-ui component have an api section. You will get list of overriding keys listed there.
Some useful links -
https://https://material-ui.com/customization/components/#overriding-styles-with-class-names
https://material-ui.com/api/app-bar/
来源:https://stackoverflow.com/questions/54827048/how-override-material-ui-style-with-hooks