Material-UI React using grid spacing overflows the container

别等时光非礼了梦想. 提交于 2020-02-07 00:06:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!