# React - 如何置入 svg ## 方法 1 - `import` 之後用 img 方式置入 - 優:可用 css 來調整 img 樣式大小等,很方便易懂 - 缺:svg 無法直接改 path 顏色 ```jsx import MyImage from './thumbnail.webp'; <img src={MyImage} alt="horse" /> ``` 做法來源: [Import and use an Image in a React component | bobbyhadz](https://bobbyhadz.com/blog/react-import-image) ## 方法 2 - 作為 component 導入 - 優:可用 css className 來設定樣式,很方便易懂 - 優:可以直接用 css 來改顏色 - 缺:不會被當成 img ,而是作為一個 component 看待 ```jsx import { ReactComponent as 要在檔案內叫的名字 } from '路徑'; ``` ```jsx ex: import { ReactComponent as Logo } from '../../assets/icons/pg-complete.svg'; <Logo className='logo-icon' /> ``` ### hover 改色例子(用 css) ```jsx // Footer.jsx import { ReactComponent as FbIcon } from '../assets/icon-facebook.svg'; <FbIcon className="social-icon" /> ``` ```scss /* style.scss */ .social-icon { path { fill: #000; } &:hover { cursor: pointer; path { fill: #fff; } } } ``` 使用物件props變顏色的方法: [Change the color of an SVG in React | bobbyhadz](https://bobbyhadz.com/blog/react-change-color-of-svg) ## 方法 3 - 直接複製 svg 程式碼,放到主檔案 可直接在路徑上改顏色`fill="#B1B1B1"`,程式碼會變一大坨,較不建議 ```jsx <div className={style.btnBookmark} onClick={() => setBookmarked((pre) => !pre)} data-active={bookmarked}> <svg width="56" height="56"> <g fill="none" fill-rule="evenodd"> <circle fill="#2F2F2F" cx="28" cy="28" r="28" /> <path fill="#B1B1B1" d="M23 19v18l5-5.058L33 37V19z" /> </g> </svg> </div> ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up