html - React 中的 SVG 图标不显示

标签 html css reactjs svg

我在 React 中上传 SVG 图标时遇到问题。我将 svg-inline-loader 添加到 webpack,但它没有显示图标。它只是显示未找到的图片。我想添加 SVG 图标作为 img src、背景图像和快捷方式图标。

编辑:

这是我的 webpack.config

module.exports = {
entry: ["whatwg-fetch", "./js/app.jsx"],
output: {
    filename: "./js/out.js"
},
devServer: {
    inline: true,
    contentBase: './',
    port: 3001
},
watch: true,

module: {
    loaders: [{
        test: /\.jsx$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
            presets: ['es2015','stage-2', 'react']
        }
    }, {
        test: /\.scss$/,
        loader: ['style-loader', 'css-loader', 'sass-loader']
        },
        {
            test: /\.(png|jpg|gif)$/,
            exclude: /node_modules/,
            use: [
                {
                    loader: 'file-loader',
                    options: {
                        name: '[path][name].[ext]'
                    }
                }
            ]
        },
        {
            test: /\.svg$/,
            loader: 'svg-inline-loader'
        }
    ]
}
};

最佳答案

jsx将您的代码转换为 vanilla javascript 并支持 svg秒。所以用同样的方法你可以制作<div> s,你可以制作<svg>

在文本编辑器中打开 svg 文件并将文件类型更改为 jsx .之后只需将代码调整为jsx即可。以下是 100% 有效的 jsx,它看起来与您最初在原生 svg 中拥有的相同。您可以删除原生 svg 中的许多元素,但如您所见,概念是相同的。

import * as React from 'react';
//I have this file named as lightning.jsx
const SVG= (
<svg
    className="control-lightning"
    viewBox="0 0 483.73 483.73"
>
    <g>
        <polygon 
            points="119.637,282.441 192.449,282.441 165.869,
            483.73 364.094,189.622 296.631,189.622 325.678,0"
        />
    </g>
</svg>
);

export default SVG;

尝试将其导入您的元素并渲染它。这将是一个无样式的闪电。

关于html - React 中的 SVG 图标不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49779235/

相关文章:

javascript - 图片幻灯片淡入淡出

javascript - React - 为什么输入字段仍然是只读的(即不可编辑),即使我已经添加了 onChange?

reactjs - 没有路线匹配位置

css - 垂直滚动不适用于移动 firefox 它说 -webkit-overflow-scrolling :touch is invalid property value

jQuery css 变量不定位容器

javascript - 每次流结束时都会延迟随机时间的 Observable

php - 如何在运行时左侧 div 为空时将右侧 div 向左移动?

html - 让中央 div 定义其他的宽度

css - HTML5 表格单元格/行与其他宽度相同

php - Prestashop 后台加载为问号