[英]How do I load SVGs directly in my React component using webpack?
I would like to render a material design icon directly in my NextButton
component using webpack. 我想使用webpack直接在我的NextButton
组件中渲染一个材质设计图标。 Here's the relevant part of my code: 这是我的代码的相关部分:
var NextIcon = require('material-design-icons/navigation/svg/production/ic_chevron_right_18px.svg');
var NextButton = React.createClass({
render: function() {
return (
<Link to={this.props.target} className='button--next'>
{this.props.label} {NextIcon}
</Link>
)
}
});
But this isn't working as I thought it would. 但这不符合我的想法。 It seems to output the svg as a string, rather than an element. 它似乎将svg输出为字符串,而不是元素。
I've tried using raw-loader
, img-loader
, url-loader
, file-loader
and svg-loader
but I can't find the correct way to do this. 我尝试过使用raw-loader
, img-loader
, url-loader
, file-loader
和svg-loader
但我找不到正确的方法来做到这一点。
Since your SVG content is stored as a string and not as a React element, you'll need to use Dangerously Set innerHTML . 由于您的SVG内容存储为字符串而不是React元素,因此您需要使用Dangerously Set innerHTML 。
var NextIcon = require('material-design-icons/navigation/svg/production/ic_chevron_right_18px.svg');
var NextButton = React.createClass({
render: function() {
return (
<Link to={this.props.target} className='button--next'>
{this.props.label} <span dangerouslySetInnerHTML={{ __html: NextIcon }} />
</Link>
)
}
});
You could perhaps work your way around this by creating a webpack loader that automatically does this for you whenever you require a SVG file. 您可以通过创建一个webpack加载器来解决这个问题,该加载器会在您需要SVG文件时自动为您执行此操作。
dangerouslySetInnerHTML.loader.js dangerouslySetInnerHTML.loader.js
module.exports = function(content) {
return (
'module.exports = require("react").createElement("span", {' +
'dangerouslySetInnerHTML: {' +
'__html: ' + JSON.stringify(content) +
'}' +
'});'
);
};
webpack.config.js webpack.config.js
loaders: [
{
test: /\.svg$/,
loader: require.resolve('./dangerouslySetInnerHTML.loader'),
exclude: /node_modules/,
},
],
The previous code snippet would then become: 之前的代码段将变为:
var NextIcon = require('material-design-icons/navigation/svg/production/ic_chevron_right_18px.svg');
var NextButton = React.createClass({
render: function() {
return (
<Link to={this.props.target} className='button--next'>
{this.props.label} {NextIcon}
</Link>
)
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.