如何使用webpack直接在我的React组件中加载SVG? [英] How do I load SVGs directly in my React component using webpack?

查看:546
本文介绍了如何使用webpack直接在我的React组件中加载SVG?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用webpack直接在我的 NextButton 组件中渲染一个材质设计图标。这是我的代码的相关部分:

I would like to render a material design icon directly in my NextButton component using webpack. 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>
    )
  }
});

但这不符合我的想法。它似乎将svg输出为字符串,而不是元素。

But this isn't working as I thought it would. It seems to output the svg as a string, rather than an element.

我尝试使用 raw-loader img-loader url-loader file-loader svg-loader 但我找不到正确的方法。

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.

推荐答案

由于您的SVG内容存储为字符串而不是React元素,因此您需要使用危险地设置innerHTML

Since your SVG content is stored as a string and not as a React element, you'll need to use 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>
    )
  }
});

你可以通过创建一个webpack加载器来解决这个问题,无论何时你自动为你做这件事需要一个SVG文件。

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.

dangerouslySetInnerHTML.loader.js

module.exports = function(content) {
    return (
        'module.exports = require("react").createElement("span", {' +
            'dangerouslySetInnerHTML: {' +
                '__html: ' + JSON.stringify(content) +
            '}' +
        '});'
    );
};

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>
    )
  }
});

这篇关于如何使用webpack直接在我的React组件中加载SVG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆