這是我在2023第十五屆 iThome 鐵人賽發表的系列文章。https://ithelp.ithome.com.tw/users/20136637/ironman/6408
要在 RN 中使用圖標可以安裝 react-native-vector-icons 這個庫,這些是它支持的圖標集:

這篇文章主要是教 react-native-vector-icons 的安裝和使用,以及如何在專案中添加自定義圖標。
安裝方式
安裝 react-native-vector-icons:
npm install --save react-native-vector-icons @types/react-native-vector-icons
Android
在 android/app/build.gradle
添加
apply from: file("../../node_modules/react-native-vector-icons/fonts.gradle")
iOS
iOS 需要手動引入圖標集的 tff 才能使用圖標。
- 打開 xcworkspace 然後對著 App 名稱的資料夾右鍵 – New Group – 名稱 Fonts

- 在
node_modules/react-native-vector-icons
中的 Fonts 資料夾找到要使用的圖標集 ttf 檔案並複製貼上到剛剛新增的Fonts
資料夾裡面:

- 接著打開
Info.plist
,對著上方 Information Property List 按右鍵-Add Row

- 輸入
Fonts provided by application

- 需要用幾個圖標集就添加幾個 item:

更詳細的請參考 官方文檔 進行設置。
基本使用
import Icon from 'react-native-vector-icons/FontAwesome';
const myIcon = <Icon name="rocket" size={30} color="#900" />;
IconButton
import Icon from 'react-native-vector-icons/FontAwesome';
const myButton = (
<Icon.Button
name="facebook"
backgroundColor="#3b5998"
onPress={this.loginWithFacebook}
>
Login with Facebook
</Icon.Button>
);
const customTextButton = (
<Icon.Button name="facebook" backgroundColor="#3b5998">
<Text style={{ fontFamily: 'Arial', fontSize: 15 }}>
Login with Facebook
</Text>
</Icon.Button>
);
查看所有可以使用的 icon:https://oblador.github.io/react-native-vector-icons/
添加自定義圖標集
比較有意思的是 react-native-vector-icons 支持使用自定義的圖標集,只需要有 svg 格式的圖像並跟著下面的步驟操作即可。
下載 font
在 fontello 將 svg 全部拖進這個區塊中:


要注意的是,它不支持彩色的 svg,所以下面這個檸檬就會變成一坨黑塊:
原圖 | icon |
---|---|
![]() | ![]() |
建議使用純線條的 icon,比如這些:

如果需要有顏色的 icon,那還是單獨將它導出為 svg 然後直接在 RN 中使用 react-native-svg 來渲染這些圖標比較方便。
選中要使用的 icon 後點 Customize Names 標籤頁可以自定義每個圖標的名稱,以及右上角的設置可以修改名稱前綴:

都設定好之後在右上方按下載,打開後會有以下內容,我們會需要用到的只有 fontello.ttf
和 config.json
:

添加圖標集到專案中
首先在專案中新建 fonts
資料夾,把 config.json
放進去。

Android
將 ttf 放入 android/app/src/main/assets/fonts
即可。
iOS
將 ttf 添加到 Resources

並在 Fonts provided by application
新增一個 item 輸入 ttf 的檔名(跟安裝步驟一樣)

使用方式
createIconSetFromFontello(fontelloConfig)
即可在 App 中使用自定義的圖標集:
// CustomIcon.tsx
import { createIconSetFromFontello } from 'react-native-vector-icons'
import fontelloConfig from './fonts/config.json'
const CustomIcon = createIconSetFromFontello(fontelloConfig)
<CustomIcon name="user" size={size} {...} />