react 的jsx中 svg 一些写法

import React from 'react';
import './style.css';
import './hui.css';
import test from './test.svg';
import { ReactComponent as Check } from './check.svg';
export default function App() {
  return (
    <div>
      <div style={{  '50px', height: '50px', background: 'pink' }}>
        test
      </div>

      <div
        style={{
           '500px',
          height: '500px',
          background: url(test),
        }}
      >
        test
      </div>

      <div class="huistyle">huistyle</div>

      <a href={test}>查看 SVG 文件</a>
      {/* <img src={require('./check.svg')} /> */}
      {/* <img src={test} /> */}

      <object width="50px" height="50px" data={test} type="image/svg+xml" />

      {/* <Check width="10px" height="10px" /> */}
      
    </div>
  );
}

import和require一般指的引入src目录下的


一、
import test from './test.svg';
<img src={test} />
  <object width="50px" height="50px" data={test} type="image/svg+xml" />
 <a href={test}>查看 SVG 文件</a>

二、
import { ReactComponent as Check } from './check.svg';
<Check width="10px" height="10px" /> 
三、
 <img src={require('./check.svg')} />

四、背景图
import logo from './logo.svg';
单引号
 <div style = {{ '100px',height: '100px', background: 'url('+logo+')' }}>test bg2222</div>
双引号
 <div style = {{ '100px',height: '100px', background: "url("+logo+")" }}>test bg22</div>
 
   用require好像不行
 

五、
getBase64 (img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', (e) => {
    callback(reader.result)
  })
  reader.readAsDataURL(img)
}

const withBase64 = (img) => {
  const str = img.split(',');
  return str[0] + ';base64,' + btoa(decodeURIComponent(str[1]));
};
      {/* <h1 style={{ background: `url(` + logo + `)` }}>Hello World!</h1> */}
      <h1 style={{ background: `url(${withBase64(logo)}) ` }}>Hello World!</h1>


参考

https://stackoverflow.com/questions/55291138/reactjs-style-background-image-with-url

https://blog.csdn.net/qq_39512863/article/details/86607658
原文地址:https://www.cnblogs.com/dhjy123/p/15347102.html