简体   繁体   中英

how can I use svg as background image in react?

I want to use svg as background image in div, and can't find how to use!

I tried two ways.

common settings in webpack config files.

{
        test: /\.svg$/,
        use: ['@svgr/webpack','svg-url-loader'], // I tried url-loader either 
},
  1. I tried to embed src file as a props of styled-components
import styled from 'styled-components';
import categoryImage from 'src/asset/monitor-tv.svg';

export const CategoryIcon = styled.div<{
}>`
  width: 24px;
  height: 100%;
  background: url(${categoryImage}) no-repeat center;
  background-size: cover; 
` 




but it throws error in typescript compiler

Argument of type 'FunctionComponent<SVGAttributes<SVGElement>>' is not assignable to parameter of type 'Interpolation<ThemedStyledProps<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "slot" | "style" | "title" | ... 251 more ... | "onTransitionEndCapture"> & { ...; }, any>>'.
  Type 'FunctionComponent<SVGAttributes<SVGElement>>' is not assignable to type 'InterpolationFunction<ThemedStyledProps<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "slot" | "style" | "title" | ... 251 more ... | "onTransitionEndCapture"> & { ...; }, any>>'.
    Types of parameters 'props' and 'props' are incompatible.
      Type 'ThemedStyledProps<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "slot" | "style" | "title" | ... 251 more ... | "onTransitionEndCapture"> & { ...; }, any>' is not assignable to type 'PropsWithChildren<SVGAttributes<SVGElement>>'.
        Type 'ThemedStyledProps<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "slot" | "style" | "title" | ... 251 more ... | "onTransitionEndCapture"> & { ...; }, any>' is not assignable to type 'SVGAttributes<SVGElement>'.
          Types of property 'onCopy' are incompatible.
            Type '((event: ClipboardEvent<HTMLDivElement>) => void) | undefined' is not assignable to type '((event: ClipboardEvent<SVGElement>) => void) | undefined'.
              Type '(event: ClipboardEvent<HTMLDivElement>) => void' is not assignable to type '(event: ClipboardEvent<SVGElement>) => void'.
                Types of parameters 'event' and 'event' are incompatible.
                  Type 'ClipboardEvent<SVGElement>' is not assignable to type 'ClipboardEvent<HTMLDivElement>'.
                    Type 'SVGElement' is missing the following properties from type 'HTMLDivElement': align, accessKey, accessKeyLabel, autocapitalize, and 17 more.ts(2345)
Peek Problem (Alt+F8)
No quick fixes available


  1. I tried to embed as path where svg located.
import styled from 'styled-components';
import categoryImage from 'src/asset/monitor-tv.svg';

export const CategoryIcon = styled.div<{
}>`
  width: 24px;
  height: 100%;
  background: url('src/asset/monitor-tv.svg') no-repeat center;
  background-size: cover; 
` 

and the browser show me this error

Error: Invalid tag: data:image/svg+xml,%3c!doctype svg public '-//w3c//dtd svg 1.0//en' 'http://www.w3.org/tr/2001/rec-svg-20010904/dtd/svg10.dtd'%3e %3csvg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' id='body_2' width='200' height='64'%3e %3cg transform='matrix(1 0 0 1 0 0)'%3e %3cg transform='matrix(1 0 0 1 0 0)'%3e %3cpath d='m0 0l0 64l200 64l200 0' stroke='none' fill='%23ffffff' fill-rule='evenodd' /%3e %3c/g%3e %3cimage x='0' y='0' xlink:href='data:image/png;base64,ivborw0kggoaaaansuheugaaamgaaabacaiaaadq2a98aaaacxbiwxmaaa7daaaowwhhb6hkaaakfuleqvr4no2cauwuarqa8tbg44egax94rdemzo/rginhkmywiuzhddzqdbmixin4grmiqyyrk0tmxhuxzby9abcuidsmojamamzhfvaqekvpmoam6ay5upu+t/bt/qqsuhtstiuq3vmefd+q33qp71ufv6oqgr9+diyc/oguapp/crylqwlylawlylewlidfwlacfgtdcvgsdcx4nlg2w3+pxitvm5ktdjecgrpfekummv7jscfuw9xn19nqvmfx/vkojspt0l0xxg0+i1adwl3jbgcprw6br7mfnptqxr3ggd8qs6u3rwwmvo5a02sjhreyhw+ivfjwmbrv9napxej3jzhb+izyvzr9qkwrj7fyzmi3xniylh/m4a0zftzj8vtilhxdlidfqyvjcupwlnr2csnevdmoboml4/e6vvtosgcplzxcebehox9exvtlttaalrnpzvfzfkqubbivloibu/r0fywzbkaizenre8xfvfrsszqxxo+imhz0kjn1jusofufhum66qsv4av1iwxq6zldfuspftmyvvjdkzer+7svocracxoixnkc/wb3ffz+mvaijdh+mu0zmykbflo7mzr8uq/hzz+kuezmy6berotr6g2i1ffkl+uf0fr1iwxzq3mrnarrkxgwp/wkpnz9/frawvfjyjayurldoc9tvftsqntcwcdqphq9zw6+qtl20/gkwbqbfleb++3bd7nldwdv66pt9xzn+frpvfiv3ailfbiln+/hqxtqyiragrqnh79xzfxhivoq9bl1vysgr80rx1nuq1j503qexeiwrtbelye7t7xv2dfzur2bp1rhztmeru0uheqtclktlwzihyjzyciny3lrunta21mowkoowweph73e16mxjhmlyrve1glcwuszazreoy8q6c3lggbzvnkivcxljvv2tf0qqb6wrtsxqmfss4zhowma/wcq7265rprswjht8qky+vj6rshtmzbmtvqscjd2f7tdqep54squl1fa6xqpnarw5npwqjhcqxwfwpfvxmc39fxyvxmgdjkcg1wnkpvx83qfeqq6ujoulcwkjuxr16vnz56noqqe1ozcm9gy3/9i3nsng1pwnum9196chby6yujrky4kdcmp4d+yv05v0rl/9khltxcrozm5pavm7di2ifr8ff/hirsp6gwwxcl7iuxcwelpnufasrglqmlc6hwuyjxaxy2wxwekhukluwsdhjx4ljycvcbb8+fksrcypvgoweg1wqoxurdcsbywgj2i1rwrlwbxqs/xdr/jzafyzzkaaywmxjtxrdp1868ua4jvgqiyj2vojgntnorhabb1u7qvroh7fdmhtbib2uyjxyu3atevqoumntpwah+cjxwkzo3futgnt/bzaabyygcgwi73b6ujf+vpdnqcxwfdn87s1jjhv16bz5o796ap5qliror8nxijw3djoerr4dis32uksmcoyc4fves24vgbykoaa822bygcizzjllljhjx8hpbzt27z169b8/hwuda0n9rtg8elfcqkjxu+xecursg7/6k4t4t8ttmll13alliqjtu/fakhilw2huzbuwpf2fiexqira/p2wrt/yl37ongcnt0gs9iw23be4av17or429qigwaykojyujk4jxuy4yc+5+d/3b6pd+7wdkomvjei9jovk1dbzh49zyl26dak0mjvr1owzm8rkys6dowfb7du3+5gor6+vrkxmtezmghgy/ekqyg3tclfgvkss9j183ynayztejlqlcyfv2e99ilgo5wvj15coddty9m/bnjgwvuiss2xtkayhrip3cqgnfqtug9c9zlfq8m3g706ijulvv+tiptf/xlmsvvu29z3mkchhbw7drx9micxj8qibynw6e/ysbf++fdlhwgqujiymtfqtmj5freqcpxq0okdak/0sysf/dpjqhnqbhaehvq/wdcrxsbbum3+xrt0gx4a0pfjanwpbif7zw/veh8t6e7nktyd207um2p219djvlibhailtgixksaaloizeybd80fk+i2gx/g+3b32hf0y1vanu75w/ophcclesa7fxu7q6xowzq7gfs3gu9/f3h49bquho44yng1aswahmeevug+drrnuo4/3zgrrfoyacjvuh9uqstcydsasfjbycp5ban4bjra3ixgmyhrakumaixejzjryjkqd9vn/9excrjsxl4mgdxcxf6oponturvbdyinkmt58okedgyjvntnr16tjywjrz584dr9tguvinf7ippdavkhp4cr19i5f7mwj1qoxbhd6gcrggzh7hbeswk+kmfrpls3xkc/7gv0hw5p2w/og5uqo0khpk2b/vqragni1btkrfrsku9q9ixllybywjcagg54wdoxacisehcfxexk7mjglpav6pwxoxrj6r2cxiflwbgbugox1c6i/vf++eiwvkv7/bjg5jz6odo5nymk/bmwz6ybm0+hoc1amjsd9akhelwyaa5fga5r0xcq/8fy0uosxky8urqqpauhdhgguljh07dvnyzqheuhabjiegkabvapfgscxg48ankmllcr1siedi9wpmse52/lgzplro+gixdczrzkzdaugirzzeausx7hb3o1fanzljlbli9w5/fq8s19sg4r4cuqedylvxv69curipmmfohi3gvmm6ffo0ffyyzamrjpfium6anwtqbnzk8+fprzter1rimfnqzsrtl3nrkmrhfhgxhjlj+y9oj9kkle7dlqoj0gircr7k+q/byt9itntb5epk7besf2vixwrvyxudd3cgdhrl4i6uwm9+zfgqo33ku+pid3xgv1jghprqivdrdrorn16x1gr1+phjkttr0deochs9j7e4ha7kcq0njylohgslxrrtojgeqfmakykpcfyyonvqxv0diuzdu9djrmrksitwqlwricdsb8k6ypggzwldvxsx/aglcymisjb3equ0tnrpjquufru5lcuwjijmsdbsfd++furk/fr1tmll5ua6iiuucleqvmcjwjhgm2gwkziyeuritk4mishbwrbztggreulpt3cvy2q1tpkybyi5otmjwjhgm2gwa9myzsbhzmymeqkkcolivhnziaga1zygmwdp0quqphdgwoivi/eyosuymuwtj04eoupksojgzjkzncq6efkkw7hqaece2zdmgu6xamtrircwumrms40bn85jrjiygjrgdgkpqako3t5oz1mlzddqkvzawhoyo7oze0wusiwk+pv7e2nh4efuxuibq8cl789gvmuhxnpbjwg55ed4qwzfigc1kyznitlqqw3a5mmtyt8efhag4nadsuveuowtxpldyibgk8tkx2cg4jpewma+diwwhhkwwbhkwgjhkaglhaeelbagerbygeraymeoayufoqqsfoys/gdsdb6xmpuupqaaaabjru5erkjggg==' width='200' height='64'/%3e %3c/g%3e %3c/svg%3e
    at validateDangerousTag (C:\Users\Desktop\web\fe\node_modules\react-dom\cjs\react-dom-server.node.development.js:2748:15)
    at ReactDOMServerRenderer.renderDOM (C:\Users\Desktop\web\fe\node_modules\react-dom\cjs\react-dom-server.node.development.js:3767:5)
    at ReactDOMServerRenderer.render (C:\Users\Desktop\web\fe\node_modules\react-dom\cjs\react-dom-server.node.development.js:3484:21)
    at ReactDOMServerRenderer.read (C:\Users\Desktop\web\fe\node_modules\react-dom\cjs\react-dom-server.node.development.js:3373:29)
    at renderToString (C:\Users\Desktop\web\fe\node_modules\react-dom\cjs\react-dom-server.node.development.js:3988:27)
    at app.get (webpack:///./src/server.tsx?:71:87)
    at Layer.handle [as handle_request] (C:\Users\Desktop\web\fe\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Desktop\web\fe\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Desktop\web\fe\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Desktop\web\fe\node_modules\express\lib\router\layer.js:95:5)

You can do this setting it as the background of an element:

background: url(data:image/svg+xml;base64,PHNBLAHBLAHBLAH)
    no-repeat center center;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM