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

React 0.14结合Material-UI 0.15.0版本中如何修改Snackbar的显示位置(从底部改为右上角)

如何调整Material-UI 0.15.0 Snackbar到右上角(React 0.14)

嘿,刚好对这个旧版本的Material-UI有点印象——0.15.x的Snackbar确实没有内置的位置配置属性,不过咱们可以通过自定义样式轻松搞定右上角的布局,给你两种实用的方案:

方案一:直接通过style属性自定义定位

直接给Snackbar组件添加行内样式,覆盖它默认的底部定位:

<div>
  <button onClick={this.handleTouchTap}> SHOW NOTIFICATION </button>
  <Snackbar
    open={this.state.open}
    message="Event added to your calendar"
    autoHideDuration={4000}
    onRequestClose={this.handleRequestClose}
    style={{
      position: 'fixed',
      top: 20, // 距离顶部的距离,可按需调整
      right: 20, // 距离右侧的距离,可按需调整
      bottom: 'auto', // 覆盖默认的bottom: 0样式
      maxWidth: 'none' // 可选,防止长消息被截断
    }}
  />
</div>

原理很简单:默认Snackbar是position: fixed且bottom: 0,我们把bottom设为auto,再指定top和right的数值,就能把它拉到右上角了。

方案二:使用自定义CSS类(适合复用场景)

如果需要在多个地方使用这个样式,定义一个CSS类更方便:

首先在你的样式文件里添加:

.custom-top-right-snackbar {
  position: fixed !important;
  top: 20px;
  right: 20px;
  bottom: auto !important;
}

这里加!important是为了确保自定义样式能覆盖Material-UI默认的优先级更高的样式。

然后在组件里引用这个类:

<Snackbar
  open={this.state.open}
  message="Event added to your calendar"
  autoHideDuration={4000}
  onRequestClose={this.handleRequestClose}
  className="custom-top-right-snackbar"
/>

两种方案都能解决你的问题,选哪种看你的实际需求就好~

内容的提问来源于stack exchange,提问作者React-Developer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:52:49