2015-06-15 24 views
10

Vorrei rendere un'icona di material design direttamente nel mio componente NextButton usando il webpack. Ecco la parte rilevante del mio codice:Come caricare gli SVG direttamente nel mio componente React usando il webpack?

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

Ma questo non funziona come pensavo. Sembra che l'uscita svg sia una stringa, piuttosto che un elemento.

Ho provato con raw-loader, img-loader, url-loader, file-loader e svg-loader, ma non riesco a trovare il modo corretto di fare questo.

risposta

16

Dal momento che il contenuto SVG è memorizzato come una stringa e non come un elemento Reagire, avrete bisogno di utilizzare 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> 
    ) 
    } 
}); 

Si potrebbe forse lavorare il vostro modo intorno a questo con la creazione di un caricatore webpack che fa automaticamente per voi ogni volta che avete bisogno di un file in formato SVG.

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/, 
    }, 
], 

Il codice precedente frammento di diventerebbe:

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

Questo ha aiutato molto , Grazie! – dduupp

+1

Nota rapida: dovrebbe essere '__html' not' _html' – Chris

+0

Grazie, l'ho risolto. –

Problemi correlati