使用SVG的自定义Material-UI按钮?

问题描述

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

enter image description here

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

解决方法

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

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作为组件导入,并将其传递到component上的SvgIcon道具,并使用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.