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

Material-UI Grid内React Router Link居中后(xs=7)失效问题

Material-UI Grid中react-router-dom Link组件在xs=7时失效的问题解决

在使用Material-UI的Grid系统搭配react-router-dom的Link组件时,出现了一个奇怪的现象:当Grid item的xs属性设为7,并且通过display: flex和justifyContent: 'center'让Link水平居中时,Link会完全失效——鼠标悬停不会显示手型指针,点击也没有任何响应。但把xs改成6时,Link又能正常工作。

导入代码

import { Link } from 'react-router-dom';
import { Grid } from '@mui/material';

正常工作的代码

<Grid container xs={12}>
  <Grid item xs={6} style={{ display: 'flex', justifyContent: 'center' }}>
    <Link to="#testimony">Testimony</Link>
  </Grid>
</Grid>

失效的代码

<Grid container xs={12}>
  <Grid item xs={7} style={{ display: 'flex', justifyContent: 'center' }}>
    <Link to="#testimony">Testimony</Link>
  </Grid>
</Grid>

问题原因

这种情况大概率是元素层级覆盖导致的:当Grid item的宽度(xs=7)超过容器的某个临界值时,可能有其他同级或父级元素(比如相邻未定义宽度的Grid item、容器的默认间距元素等)覆盖在了Link上方,阻断了鼠标事件传递。

解决方案

  • 给Link提升层级
    直接给Link设置z-index,确保它在视觉层级上处于顶层,避免被其他元素遮挡:

    <Grid container xs={12}>
      <Grid item xs={7} style={{ display: 'flex', justifyContent: 'center' }}>
        <Link to="#testimony" style={{ zIndex: 10 }}>Testimony</Link>
      </Grid>
    </Grid>
    
  • 修正事件传递规则
    给Grid item设置pointer-events: none,让鼠标事件直接穿透到内部的Link,同时给Link恢复pointer-events: auto确保事件能正常触发:

    <Grid container xs={12}>
      <Grid item xs={7} style={{ display: 'flex', justifyContent: 'center', pointerEvents: 'none' }}>
        <Link to="#testimony" style={{ pointerEvents: 'auto' }}>Testimony</Link>
      </Grid>
    </Grid>
    
  • 明确容器内所有元素宽度
    检查Grid容器内是否有未设置宽度的元素,它们可能会自动填充剩余空间并覆盖当前Link所在的item。可以给所有Grid item明确分配宽度,避免元素重叠:

    <Grid container xs={12}>
      <Grid item xs={7} style={{ display: 'flex', justifyContent: 'center' }}>
        <Link to="#testimony">Testimony</Link>
      </Grid>
      {/* 明确占据剩余空间的item */}
      <Grid item xs={5}></Grid>
    </Grid>
    

内容的提问来源于stack exchange,提问作者Stephen Scott Moore

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:15:07