如何使用Webpack与React内联多个SVG? [英] How to inline multiple SVGs with React using Webpack?
问题描述
比方说,我想在我的React应用程序中内嵌很多或更多的SVG.现在,我正在使用 svg-react-loader 这样导入它们
Let's say I have a dozen or more SVGs that I want to inline in my React app. Right now, I'm using svg-react-loader to import them like this.
import Svg1 from "!babel!svg-react!../../images/sdg1.svg";
import Svg2 from "!babel!svg-react!../../images/sdg2.svg";
import Svg3 from "!babel!svg-react!../../images/sdg3.svg";
import Svg4 from "!babel!svg-react!../../images/sdg4.svg";
...等等.我需要在每个事件处理程序上设置事件处理程序并将鼠标悬停在事件上.此外,它们中的一个时被选择我想改变其透明度.
...and so on. I need to set event handlers on each of them and hover events. Moreover, when one of them is selected I want to change its opacity.
经过几个小时和许多次失败的实验,我尝试过的唯一有效的方法就是将它们全部呈现在这样的父组件中.
After several hours and as many failed experiments, the only thing I've tried that works is to render them all inside a parent component like this.
const Icon = React.createClass({
//Callback that updates the state of a parent component
clickHandler() {
this.props.handler(this.props.svg)
}
render() {
const icons = [
<Svg1 className="svg1" opacity={this.props.svg === this.props.currentSvg ? 1 : 0.3} />
<Svg2 className="svg2" opacity={this.props.svg === this.props.currentSvg ? 1 : 0.3} />
<Svg3 className="svg3" opacity={this.props.svg === this.props.currentSvg ? 1 : 0.3} />
<Svg4 className="svg4" opacity={this.props.svg === this.props.currentSvg ? 1 : 0.3} />
];
return (
<div className="icon" onClick={this.clickHandler}>
{icons[this.props.svg]}
</div>
);
}
});
同样,这行得通,但是我敢肯定这不是React想要的方式.有没有一种方法可以迭代通过这种方式创建的SVG组件以为其分配属性?
Again, this works but I'm sure this isn't the way React intended. Is there a way to iterate over SVG components created this way to assign them properties?
推荐答案
one way is to just put them in an array and use React.createElement:
const icons = [Svg1, Svg2, Svg3, Svg4];
return (
<div className="icon" onClick={this.clickHandler}>
{icons.map((svg, i) => React.createElement(svg, {
className: "svg"+i,
opacity: (this.props.svg === this.props.currentSvg ? 1 : 0.3)
})}
</div>
);
另一种选择,因为您正在使用Webpack,所以要利用其动态需求功能.
Another option, since you are using Webpack is to make use of their dynamic require functionality.
基本上,您可以为webpack提供文件通配符以与您的应用捆绑在一起,然后在运行时动态并同步地要求它们:
Basically you can give webpack a wildcard of files to bundle with your app and then at runtime dynamically and synchronously require them:
// right below your import statements
const reqSvgs = require.context("../../images", false, /\.svg$/);
// now anywhere in your code you can:
const arrayOfSVGFilenames = reqSvgs.keys();
const specificSVG = reqSvgs("../../images/svg1.svg");
const allSVGsInAnArray = reqSvgs.keys().map(reqSvgs);
这篇关于如何使用Webpack与React内联多个SVG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!