问题描述
我目前正在这样做:
class Checked extends React.Component {
render() {
return (
<svg width="24" fill="#00ea00" height="24" viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
</svg>
);
}
}
但是我想做这样的事情:
But I would like to be doing something like this:
import imgTable from '../img/catering_table.svg'
class Checked extends React.Component {
render() {
return imgTable;
}
}
为什么这不起作用?我在这里返回变量而不是实际内容吗?我本以为两者是等效的.
Why does this not work? Am I returning the variable here and not the actual contents? I would have thought the two are equivalent.
PS:Webpack设置正确,我在该文件的其他位置使用了导入,所以不是那样.(顺便说一下,我在这里使用GatsbyJS)
PS: Webpack is set up correctly, I am using imports somewhere else in that file, so it's not that. (I am using GatsbyJS here by the way)
推荐答案
选项1 :使用无状态组件包装:
Option 1: Wrap with a stateless component:
const ImgTable = () => (
<svg width="24" fill="#00ea00" height="24" viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
</svg>
);
export default ImgTable;
现在您可以将其作为组件导入:
Now you can import it as a component:
import ImgTable from '../img/ImgTable'
class Checked extends React.Component {
render() {
return <ImgTable />;
}
}
选项2 :使用 dangerouslySetInnerHTML (注意名字).但是,您需要在导入时使用 babel-plugin-transform-svg-import-to-string :
Option 2: Use dangerouslySetInnerHTML (notice the name). However, you'll need to convert the SVG to string on import using something like babel-plugin-transform-svg-import-to-string:
import imgTable from '../img/catering_table.svg' // this will return a string
class Checked extends React.Component {
render() {
return <div dangerouslySetInnerHTML={{__html: imgTable }} />;
}
}
这篇关于React:将SVG内容作为变量返回吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!