【问题标题】:Replace image element with inline svg in React在 React 中用内联 svg 替换图像元素
【发布时间】:2017-11-01 13:34:00
【问题描述】:

我正在尝试创建一个将图像元素更改为内联 svg 元素的 React 组件。我想这样做,以便我可以从文件中插入 svg 元素,以便使用 css 处理样式。

同样重要的是,我正在为我的项目使用 create-react-app 存储库,并且希望能够在不弹出项目的情况下执行此操作。

变量req 返回一个有效的svg 元素,我设置了this.state.response,然后我尝试更新它,但是很好......它不起作用。使用下面的代码,我得到以下错误:

 A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

代码:

class Svg extends Component {

constructor(props) {
    super(props);
    this.state = {
        response: undefined
    };
    this.toSvg(this.props.src);
}

toSvg(img) {
    const imageUrl = img;
    let self = this;

    // Create new XML Http Request to get data
    let request = new XMLHttpRequest();
    request.open('GET', imageUrl, true);

    request.onreadystatechange = function() {
        if (this.readyState === 4) {
            if ((this.status >= 200) && (this.status < 400)) {
                // Success!
                // Returns the HTML object
                let req = request.responseXML.getElementsByTagName('svg')[0];

                self.setState({
                    response : req
                });
            } else {
                // Error :(
            }
        }
    };

    request.send(null);
}

render() {
    if (this.state.response === undefined) {
        console.log('no response rendering standard img');
        return <img src={this.props.src} alt='icon' />;
    }
    else {
        console.log('now we update');
        return this.state.response;
    }
}
}

如果有人知道如何处理 svg 元素以替换 img 元素而不会出现错误,那就太棒了。

【问题讨论】:

    标签: javascript html reactjs svg xmlhttprequest


    【解决方案1】:

    使用svg-inline-loader

    # add npm package
    npm install svg-inline-loader --save-dev
    
    # configure webpack loader
    {
        test: /\.svg$/,
        loader: 'svg-inline-loader'
    }
    
    # using in react code
    <InlineSVG src={require("file.svg")} />
    

    编辑:

    目前在create-react-app 中使用的是url-loader

    因此您可以手动配置文件大小限制以检索 数据 URL

    require("url-loader?limit=10000!./file.svg");
    

    【讨论】:

    • 忘了提到我正在使用 create-react-app 所以希望能够在不弹出我的项目的情况下使用:D 我会更新我的问题
    • 后一种方法在create-react-app中导致如下错误:“Unexpected '!'在 'url-loader?limit=10000!./drawing.svg'. 不要使用 import 语法来配置 webpack loader" import/no-webpack-loader-syntax
    【解决方案2】:

    最终使用react-svg

    https://www.npmjs.com/package/react-svg

    像魅力一样工作。

    【讨论】:

      【解决方案3】:

      现在可以在 create-react-app 2.0 中使用特殊的导入语法:

      import logoUrl, { ReactComponent as Logo } from './logo.svg';
      

      参考资料:

      【讨论】:

        猜你喜欢
        • 2018-08-07
        • 2012-09-27
        • 1970-01-01
        • 2019-07-23
        • 1970-01-01
        • 2015-06-30
        • 1970-01-01
        • 2014-05-13
        • 1970-01-01
        相关资源
        最近更新 更多