svg - 如何使用 Webpack 通过 React 内联多个 SVG?

标签 svg reactjs webpack

假设我有十几个或更多 SVG,我想将其内联到我的 React 应用程序中。现在,我正在使用svg-react-loader像这样导入它们。

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";

...等等。我需要在每个事件上设置事件处理程序和悬停事件。此外,当选择其中之一时,我想更改其不透明度。

经过几个小时和多次失败的实验后,我尝试过的唯一有效的方法是将它们全部渲染在像这样的父组件中。

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 组件来为其分配属性?

最佳答案

一种方法是将它们放入数组中并使用 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,另一个选择是利用它们的 dynamic require功能。

基本上,您可以为 webpack 提供一个文件通配符来与您的应用程序捆绑在一起,然后在运行时动态同步地需要它们:

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

关于svg - 如何使用 Webpack 通过 React 内联多个 SVG?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38353987/

相关文章:

javascript - 是否可以使用 `require.context` 为 Webpack 进行动态导入?

svg - 如何获得转换/旋转的 SVG 路径点

javascript - 收到预期赋值或函数调用却看到表达式 no-unused-expressions 的错误?

javascript - Ag-Grid 服务端渲染问题 : ReferenceError: HTMLElement is not defined

reactjs - Redux store 正在更新,但组件没有重新渲染

reactjs - 我可以仅使用 webpack 将代码块标记为生产或开发吗?

javascript - 使用闭包编译器和已编译的 vue.js 模板

css - Chrome 神秘地将 SVG 位置降低了 2px

html - d在svg路径中是什么意思?

css - 如何使用 svg 形状来遮盖图像?