React使用svg方法

344 阅读1分钟

1.使用 <img>标签

import React from 'react';
import ReactLogo from './logo.svg';

const App = () => {
  return (
    <div className="App">
      <img src={ReactLogo} alt="React Logo" />
    </div>
  );
}
export default App;

弊端:不能在<img>中自定义样式,适用于静态logo。

2.使用<svg>标签

import React from 'react';

const App = () => {
  return (
    <div className="App">
      /* svg */
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
        <g fill="#61DAFC">
          <circle cx="420.9" cy="296.5" r="45.7"/>
          <path d="M520.5 78.1z"/>
        </g>
      </svg>
    </div>
  );
}
export default App;

弊端:svg必须以文本格式放在代码中

3.使用ReactComponent, 将svg作为组件导入

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

function App() {
  return (
    <div className="App">
      <Logo />
    </div>
  );
}
export default App;

4.JSX中使用svg标签

export default function App() {
  return (
    <svg
        className="w-10 h-10 text-gray-800 dark:text-white"
        aria-hidden="true"
        xmlns="http://www.w3.org/2000/svg"
        fill={fill}
        width={width}
        height={height}
        viewBox="0 0 24 24">
        <path
            stroke="currentColor"
            strokeLinecap="round"
            strokeWidth="2"
            d="M5 7h14M5 12h14M5 17h14"
        />
    </svg>
);
};
export default App;