问题
I have been developing with react-native a lot and I'm working on reactjs project now using Material-UI. I think I have a bad understanding of the layout so let me go directly to a minimal example.
I have this code in App.js
import React from 'react';
import { Container, Grid } from '@material-ui/core';
import './App.css';
function App() {
return (
<Container style={{ backgroundColor: "lightgray", flexGrow: 1 }} maxWidth="xs">
<Grid container xs={12} spacing={0} style={{ backgroundColor: 'gray' }}>
<Grid item style={{ backgroundColor: "lightgreen" }}>A</Grid>
<Grid item style={{ backgroundColor: "yellow" }}>B</Grid>
</Grid>
<Grid container xs={12} spacing={0} style={{ backgroundColor: 'black' }}>
<Grid item style={{ backgroundColor: "lightblue" }}>X</Grid>
<Grid item style={{ backgroundColor: "pink" }}>Y</Grid>
</Grid>
</Container>
);
}
export default App;
Which renders the following view.
So far good and it's what I would expect. When I change the spacing of the first grid to '2' you get this view.
As you can see, it breaks the layout (it "overflows") and I think I'm missing some fundamental concept of material ui. I would expect one of these views but not the one above
Could anybody help me to understand what is happening?
回答1:
Material UI basic-grid
import React from "react";
import ReactDOM from "react-dom";
import { Grid } from "@material-ui/core";
import "./styles.css";
function App() {
return (
<div className="App" style={{ width: "300px" }}>
<Grid container style={{ backgroundColor: "gray" }}>
<Grid item xs={2} style={{ backgroundColor: "lightgreen" }}>A</Grid>
<Grid item xs={2} style={{ backgroundColor: "yellow" }}>B</Grid>
</Grid>
<Grid container style={{ backgroundColor: "black" }}>
<Grid item xs={1} style={{ backgroundColor: "lightblue" }}>x</Grid>
<Grid item xs={1} style={{ backgroundColor: "pink" }}>y</Grid>
</Grid>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Update: since you want to use spacing
, add flexGrow
to container's parent, you can also find this in the document above
<div className="App" style={{ width: "300px", flexGrow: 1 }}>
<Grid container item spacing={12} style={{ backgroundColor: "gray" }}>
来源:https://stackoverflow.com/questions/59389787/material-ui-react-using-grid-spacing-overflows-the-container