【问题标题】:Custom Material-UI button using an SVG?使用 SVG 的自定义 Material-UI 按钮?
【发布时间】:2020-12-03 02:19:31
【问题描述】:

我正在尝试构建一个 material-ui 按钮,它有一个自定义 svg 文件作为按钮基础,如图所示:

按钮中还应包含一个“标签”,例如“提交”或“确定”或“取消”。 有什么方法可以使用 material-ui 按钮 api / buttonbase api 并实现这个自定义按钮,以便所有其余的 material-ui 按钮功能也可用(如波纹效果等)。

【问题讨论】:

  • this 会帮助你吗?
  • 嗨@hgb123,我已经浏览了那个material-ui示例,但这并没有提供任何关于使用SVG和插入按钮标签的清晰说明。

标签: reactjs svg material-ui


【解决方案1】:

您可以像这样在ButtonBase 组件中使用SvgIcon 组件:

const useStyles = makeStyles(theme => ({
  root: {
    ...theme.typography.button
  },
}));

const CustomSvgButton = props => {
  return (
    <SvgIcon {...props}>
      <rect x="0" y="0" width="200" height="100" /> // replace with your path(s)
      <text
        x="50%"
        y="50%"
        dominantBaseline="middle"
        textAnchor="middle"
        fill="white">
        {props.label}
      </text>
    </SvgIcon>
  );
};

// ...
const classes = useStyles();

<ButtonBase focusRipple className={classes.root}>
  <CustomSvgButton
    label="Submit"
    color="primary"
    style={{ width: 200, height: 100 }}
    viewBox="0 0 200 100"
  />
</ButtonBase>

我使用rect 进行演示,但您可以将其替换为您的 svg 路径。

顶部的样式是可选的,但这样文本看起来像Typography 组件。

更新

您还可以将 svg 作为组件导入并将其传递给 SvgIcon 上的 component 属性,并将文本与 flexbox 放在中间,如下所示:

import { ReactComponent as YourSvgButton } from "./yoursvgpath.svg";

// ...

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  label: {
    position: 'absolute',
    color: 'white',
  },
}));

// ...

const CustomSvgButton = props => {
  const classes = useStyles();
  return (
    <div className={classes.root}>
      <SvgIcon
        component={YourSvgButton}
        style={{ width: 200, height: 100 }}
        viewBox="0 0 200 100"
      />
      <Typography className={classes.label}>{props.label}</Typography>
    </div>
  );
};

// ...

<ButtonBase focusRipple>
  <CustomSvgButton label="Submit" />
</ButtonBase>


请注意,仅当您使用 create-react-app 时,以这种方式将 svg 作为组件导入才有效,因为 create-react-app 在后台使用 SVGR (https://github.com/gregberge/svgr)。因此,如果您不使用 create-react-app,您可以使用 webpack 和 SVGR,如文档中所述,将您的 svg 转换为 react 组件:https://material-ui.com/components/icons/#component-prop.

【讨论】:

  • 这似乎是一个好方法,但我的 svg 文件非常复杂,其中包含多个 标签和多个 标签。有什么方法可以将 svg 导入为“ReactComponent”或路径字符串,然后将 标签放入其中?
  • 是的,可以将您的 svg 导入为“ReactComponent”并将其传递给SvgIcon。我已经更新了我的答案来展示一个例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-20
  • 2021-04-26
  • 2019-08-30
相关资源
最近更新 更多