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

如何使用Material UI实现类似示例中的提示组件?

使用Material UI实现类似示例的提示组件

1. 先安装必要依赖

如果还没装Material UI相关包,执行以下命令:
npm install @mui/material @emotion/react @emotion/styled @mui/icons-material

2. 核心代码实现

用Material UI的Alert组件搭配关闭按钮、标题,就能做出和示例类似的提示效果,以下是完整的函数组件示例:

import React, { useState } from 'react';
import Alert from '@mui/material/Alert';
import AlertTitle from '@mui/material/AlertTitle';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';

// 自定义提示组件
const CustomPrompt = () => {
  // 控制提示框的显示/隐藏
  const [isVisible, setIsVisible] = useState(true);

  return (
    isVisible && (
      <Alert
        // 可选样式主题:success(绿)/warning(黄)/error(红)/info(蓝)
        severity="info"
        // 添加关闭按钮
        action={
          <IconButton
            aria-label="关闭提示"
            color="inherit"
            size="small"
            onClick={() => setIsVisible(false)}
          >
            <CloseIcon fontSize="inherit" />
          </IconButton>
        }
        // 自定义样式,比如底部间距
        sx={{ marginBottom: 2 }}
      >
        <AlertTitle>提示标题</AlertTitle>
        这里是提示组件的具体内容,你可以根据需求修改文字、样式和主题。
      </Alert>
    )
  );
};

export default CustomPrompt;

3. 自定义调整说明

  • 换主题样式:修改severity属性值,就能切换不同的颜色和默认图标
  • 自定义图标:如果不想用默认图标,可给Alert组件添加icon属性,传入自定义图标组件(比如import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined',然后设置icon={<InfoOutlinedIcon fontSize="inherit" />})
  • 调整样式:通过sx属性可以修改背景色、文字大小、间距等,比如sx={{ backgroundColor: '#f0f8ff', fontSize: '14px' }}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:35:21