问题
I want to use MUI Grid https://material-ui.com/api/grid/
and I wanted to hide one item Grid if the screen is small, so I found something called Display https://material-ui.com/system/display/
. My code looks like this
function CRUDView() {
return (
<Grid
container
spacing={1}
direction="row"
justify="center"
alignItems="center"
>
<Grid item xs={12} lg={6}>
<span>XX</span>
</Grid>
<Grid item xs={6} display={{ xs: "none", lg: "block" }} >
<span>YY</span>
</Grid>
</Grid>
);
}
I don´t uderstand why it doesn´t work (the text YY
still appears) . Can't I use display with Grid maybe? If yes then why?
回答1:
The style functions are not automatically supported by the Grid
component.
The easiest way to leverage the style functions is to use the Box component. The Box
component makes all of the style functions (such as display) available. The Box
component has a component prop (which defaults to div
) to support using Box
to add style functions to another component.
The Grid
component similarly has a component prop, so you can either have a Grid
that delegates its rendering to a Box
or a Box
that delegates to a Grid
.
The example below (based on your code) shows both ways of using Box
and Grid
together.
import React from "react";
import ReactDOM from "react-dom";
import Grid from "@material-ui/core/Grid";
import Box from "@material-ui/core/Box";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles({
gridItem: {
border: "1px solid red"
}
});
function App() {
const classes = useStyles();
return (
<Grid
container
spacing={1}
direction="row"
justify="center"
alignItems="center"
>
<Grid className={classes.gridItem} item xs={12} lg={6}>
<span>XX</span>
</Grid>
<Box
component={Grid}
className={classes.gridItem}
item
xs={3}
display={{ xs: "none", lg: "block" }}
>
<span>YY</span>
</Box>
<Grid
component={Box}
className={classes.gridItem}
item
xs={3}
display={{ xs: "none", lg: "block" }}
>
<span>ZZ</span>
</Grid>
</Grid>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
回答2:
Grid Items just setup your layout.
They don't actually display anything. The MUI display option is for hiding specific elements.
Try this:
function CRUDView() {
return (
<Grid
container
spacing={1}
direction="row"
justify="center"
alignItems="center"
>
<Grid item xs={12} lg={6}>
<span>XX</span>
</Grid>
//removed from the below Grid Item
<Grid item xs={12} lg={6}>
<span display={{ xs: "none", lg: "block" }}>YY</span>
</Grid>
</Grid>
);
}
That will hide the individual span
element even though the grid is still there.
来源:https://stackoverflow.com/questions/58189940/material-ui-grid-does-not-hide-whe-use-display