跳至主要內容

新增 Bootstrap

雖然您不必使用特定的函式庫將 Bootstrap 與 React 應用程式整合,但通常比嘗試封裝 Bootstrap jQuery 外掛程式容易得多。 React Bootstrap 是最受歡迎的選項,旨在完全與 Bootstrap 兼容。 reactstrap 也是一個好選擇,適合希望在犧牲一些功能的情況下建置較小套件的專案。

每個專案各自的說明網站都有安裝和使用它們的詳細說明。兩者都依賴於 Bootstrap CSS 檔案,因此也請安裝它

npm install bootstrap

或者您可以使用 yarn

yarn add bootstrap

src/index.js 檔案的開頭匯入 Bootstrap CSS 和任選的 Bootstrap 主題 CSS

import 'bootstrap/dist/css/bootstrap.css';
// Put any other imports below so that CSS from your
// components takes precedence over default styles.

使用自訂主題

注意:此功能搭配 react-scripts@2.0.0 以上版本使用。

有時您可能需要微調 Bootstrap(或等效套件)的視覺樣式。

react-scripts@2.0.0 開始,您可以匯入 .scss 檔案。這樣可以使用套件內建的 Sass 變數進行全域樣式偏好設定。

若要於建立 React App 中啟用 scss,你需要安裝 sass

npm install sass

或者您可以使用 yarn

yarn add sass

若要自訂 Bootstrap,請建立一個名為 src/custom.scss(或類似名稱)的檔案,並匯入 Bootstrap 原始樣式表。在匯入的檔案之前加入任何重寫。你可以參閱 Bootstrap 的說明文件 以取得可用變數的名稱。

// Override default variables before the import
$body-bg: #000;

// Import Bootstrap and its default variables
@import '~bootstrap/scss/bootstrap.scss';

注意:你可以在路徑之前加上 ~ 前綴,如上方所示,以從 node_modules 解決模組。

最後,匯入新建立的 .scss 檔案,而不是預設 Bootstrap .csssrc/index.js 檔案的開頭,例如

import './custom.scss';