You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Mantine实现页面100%宽度布局及网格组件排列?

解决方案

要实现占满100%宽度的布局并满足指定的Grid列分配需求,只需调整组件结构并使用Mantine原生的Grid和Box组件替代原有的Container和自定义grid样式,无需额外CSS:

1. 修改Dashboard组件

用Mantine的Grid(内置网格系统)替换原有的Container,通过cols、span、offset属性精准控制列分配:

import { Grid } from '@mantine/core';
import NewsComponent from '../components/NewsComponent';
import TodoList from '../components/TodoList';
import WeatherComponent from '../components/WeatherComponent';

const Dashboard = () => {
  return (
    <Grid gutter="xl" cols={4}>
      {/* WeatherComponent 占1-4列(全宽) */}
      <Grid.Col span={4}>
        <WeatherComponent />
      </Grid.Col>
      {/* TodoList 占1-2列 */}
      <Grid.Col span={2}>
        <TodoList />
      </Grid.Col>
      {/* NewsComponent 占2-4列:偏移1列后占3列 */}
      <Grid.Col span={3} offset={1}>
        <NewsComponent />
      </Grid.Col>
    </Grid>
  );
};

export default Dashboard;

2. 修改WeatherComponent组件

移除内部的Container(默认带宽度限制和内边距),改用Box组件设置内部间距,确保组件占满父容器宽度:

import axios from 'axios';
import { Weather } from '../types';
import UserForm from './UserForm';
import { Title, Text, Box } from '@mantine/core';
import { useEffect, useState, createContext } from 'react';

export const WeatherContext = createContext<any>(null);

const WeatherComponent = () => {
  const [weather, setWeather] = useState<Weather | null>();
  const fetchWeatherData = async () => {
    const response = await axios.get('http://mock-api-call/weather/get-weather');
    setWeather(response.data.result.weather);
  };

  useEffect(() => {
    fetchWeatherData();
  }, []);

  return (
    <Box p="md"> {/* 保留内边距,同时占满父容器宽度 */}
      <WeatherContext.Provider value={weather?.forcast}>
        <UserForm />
      </WeatherContext.Provider>
      <Title order={2}>Today&apos;s Weather</Title>
      <Text size="lg">
        {weather?.forcast} with a low of {weather?.min} and a high of {weather?.max}
      </Text>
      <Text size="md" data-testid="description">
        {weather?.description}
      </Text>
    </Box>
  );
};

export default WeatherComponent;

关键说明

  • Mantine的Grid组件默认是100%宽度,无需额外设置即可占满页面,gutter属性控制网格项之间的间距;
  • 原代码中的Container组件自带最大宽度限制和左右内边距,这是导致宽度无法占满的核心原因,替换为Grid和Box后即可解决;
  • 通过span控制组件占据的列数,offset控制组件的起始列位置,精准实现需求中的列分配规则。

内容的提问来源于stack exchange,提问作者meWho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 07:03:18