【问题标题】:How to inline multiple SVGs with React using Webpack?如何使用 Webpack 使用 React 内联多个 SVG?
【发布时间】:2016-11-16 04:15:42
【问题描述】:

假设我有十几个或更多的 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 组件来为其分配属性?

【问题讨论】:

    标签: svg reactjs webpack


    【解决方案1】:

    一种方法是将它们放在一个数组中并使用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);
    

    【讨论】:

    • 是的,做到了。非常感谢。很棒的答案。
    • 到目前为止,我刚刚使用 React.createElement 尝试了顶部部分(我完全应该想到的)。稍后将在此处尝试 webpack 解决方案。
    猜你喜欢
    • 2016-03-19
    • 2023-03-18
    • 2020-09-08
    • 2015-12-22
    • 2021-11-23
    • 2018-07-08
    • 2019-11-06
    • 2019-07-01
    相关资源
    最近更新 更多