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

如何用ReactJS创建图标下方带有文字的按钮?

如何用ReactJS + Material-UI创建图标在上、文字在下的垂直按钮

嘿,我看了你现有的代码,咱们来调整一下就能实现你想要的垂直按钮效果啦!你的思路是对的,但有些细节需要修正,比如Material-UI的Button默认是水平布局,还有一些样式和props的用法需要调整。

问题分析

你当前的代码里有几个小问题:

  • disableRipple 和 focusRipple 是Button的props,不是style属性,不能写在styles里
  • Button默认是水平flex布局,需要改成垂直方向才能让图标在上、文字在下
  • 样式里的color: "primary"应该作为Button的props传递,而不是写在style中
  • 图标和文字的宽度设置35px可能会让文字被截断,建议调整或者去掉固定宽度

修改后的完整代码

import React from "react";
import { withStyles } from "material-ui/styles";
import Settings from "material-ui-icons/Settings";
import Button from "material-ui/Button";
import Typography from "material-ui/Typography"; // 用Typography优化文字样式

const styles = {
  button: {
    // 改成垂直flex布局,让内容上下排列
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    height: 95,
    width: 95,
  },
  icon: {
    height: 35,
    width: 35,
    marginBottom: 8, // 给图标和文字之间加间距
  },
  buttonText: {
    textAlign: "center",
    fontSize: 12, // 可按需调整文字大小
  },
};

const VerticalIconButton = ({ classes }) => (
  <Button
    className={classes.button}
    color="primary" // 正确传递color属性
    disableRipple // 正确传递disableRipple属性
    focusRipple // 正确传递focusRipple属性
    onClick={() => console.log("按钮被点击啦")} // 示例点击事件
  >
    <Settings className={classes.icon} />
    <Typography className={classes.buttonText} variant="caption">
      设置
    </Typography>
    {/* 不用Typography的话也可以用span:<span className={classes.buttonText}>设置</span> */}
  </Button>
);

export default withStyles(styles)(VerticalIconButton);

关键调整说明

  1. 垂直布局设置:在button样式里添加display: flex、flexDirection: "column",让按钮内部元素垂直排列,再用alignItems: "center"和justifyContent: "center"让内容在按钮里居中。
  2. Props正确传递:把disableRipple、focusRipple、color这些Button的专属props从style里移出来,直接作为Button的属性传递。
  3. 样式优化:给图标添加marginBottom拉开和文字的距离,文字用textAlign: "center"确保居中,去掉不必要的固定宽度避免文字截断。
  4. Typography的使用:Material-UI的Typography组件可以帮你统一文字样式,当然你也可以直接用span配合自定义样式。

这样调整后,你就能得到一个图标在上、文字在下的垂直按钮啦!如果需要调整大小或者颜色,直接修改styles里的对应属性就好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:51:06