问题
I've got an SVG file and I want to make an SvgIcon component out of it, how should I do that?
In the documentation, all the examples use either predefined Material Icons or a strange notation of <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />
which I have no idea what it is!
回答1:
<path />
is an SVG path, i.e. the internal bits of the SVG. the SvgIcon
component really should be able to take a path, but it doesn't :(
instead you can create a component like https://github.com/callemall/material-ui/blob/56c113217d7d05d8bb0712771b727df81984d04b/src/svg-icons/action/home.js
with your svg source in place of the path
. (I recommend minifying it a bit using https://jakearchibald.github.io/svgomg/)
回答2:
To use a SVG file as an icon, I used the <Icon/>
component with an <img/>
element inside, setting the height: 100%
to the img
element and textAlign: center
to the root
class of the <Icon/>
component did the trick:
JSX:
import Icon from '@material-ui/core/Icon';
import { makeStyles } from '@material-ui/styles';
...
<Icon classes={{root: classes.iconRoot}}>
<img className={classes.imageIcon} src="/graphics/firebase-logo.svg"/>
</Icon>
Styles:
const useStyles = makeStyles({
imageIcon: {
height: '100%'
},
iconRoot: {
textAlign: 'center'
}
});
Result:
回答3:
To obtain the path for SvgIcon, open svg file with the text editor and copy the corresponding path expression.
回答4:
The solution that worked for me is the following
import React from 'react';
import pure from 'recompose/pure';
import {SvgIcon} from '@material-ui/core';
let smile = (props) => (
<SvgIcon {...props} >
<path d="M256,32C132.281,32,32,132.281,32,256s100.281,224,224,224s224-100.281,224-224S379.719,32,256,32z M256,448
c-105.875,0-192-86.125-192-192S150.125,64,256,64s192,86.125,192,192S361.875,448,256,448z M160,192c0-26.5,14.313-48,32-48
s32,21.5,32,48c0,26.531-14.313,48-32,48S160,218.531,160,192z M288,192c0-26.5,14.313-48,32-48s32,21.5,32,48
c0,26.531-14.313,48-32,48S288,218.531,288,192z M384,288c-16.594,56.875-68.75,96-128,96c-59.266,0-111.406-39.125-128-96"/>
</SvgIcon>
);
smile = pure(smile);
smile.displayName = 'smile';
smile.muiName = 'SvgIcon';
export default smile;
Check this example of material ui icon
回答5:
If making more than one icon, you may not want to repeat all the boilerplate in the example referenced in the accepted answer. You can use a wrapper component generator like:
const wrapSvgPath = (path, viewBox='0 0 24 24') => (props) => (
<SvgIcon {...props} viewBox={viewBox}>{path}</SvgIcon>
)
used like:
const facebookPath = (<path
d="M17,2V2H17V6H15C14.31,6 14,6.81 14,7.5V10H14L17,10V14H14V22H10V14H7V10H10V6A4,4 0 0,1 14,2H17Z" />
)
export const FacebookIcon = wrapSvgPath(facebookPath)
来源:https://stackoverflow.com/questions/38510443/how-to-use-an-svg-file-in-a-svgicon-in-material-ui