您可以像这样在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.