Skip to main content

添加 Bootstrap

虽然你不必使用任何特定的库来将 Bootstrap 与 React 应用集成,但它通常比尝试封装 Bootstrap jQuery 插件更容易。React Bootstrap 是最受欢迎的选项,力求与 Bootstrap 完全对等。对于以牺牲某些功能为代价寻求较小构建的项目,reactstrap 也是一个不错的选择。

¥While you don’t have to use any specific library to integrate Bootstrap with React apps, it's often easier than trying to wrap the Bootstrap jQuery plugins. React Bootstrap is the most popular option that strives for complete parity with Bootstrap. reactstrap is also a good choice for projects looking for smaller builds at the expense of some features.

每个项目各自的文档站点都有安装和使用它们的详细说明。两者都依赖于 Bootstrap css 文件,所以也要安装它:

¥Each project's respective documentation site has detailed instructions for installing and using them. Both depend on the Bootstrap css file so install that as well:

npm install bootstrap

或者你可以使用 yarn

¥Alternatively you may use yarn:

yarn add bootstrap

src/index.js 文件的开头导入 Bootstrap CSS 和可选的 Bootstrap 主题 CSS:

¥Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your src/index.js file:

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

使用自定义主题

¥Using a Custom Theme

注意:react-scripts@2.0.0 及更高版本提供此功能。

¥Note: this feature is available with react-scripts@2.0.0 and higher.

有时你可能需要调整 Bootstrap(或等效包)的视觉样式。

¥Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).

react-scripts@2.0.0 开始,你可以导入 .scss 个文件。这使得使用包的内置 Sass 变量作为全局样式首选项成为可能。

¥As of react-scripts@2.0.0 you can import .scss files. This makes it possible to use a package's built-in Sass variables for global style preferences.

要在 Create React App 中启用 scss,你需要安装 sass

¥To enable scss in Create React App you will need to install sass.

npm install sass

或者你可以使用 yarn

¥Alternatively you may use yarn:

yarn add sass

要自定义 Bootstrap,请创建一个名为 src/custom.scss(或类似文件)的文件并导入 Bootstrap 源样式表。在导入的文件之前添加任何覆盖。你可以参考 Bootstrap 的文档 以获取可用变量的名称。

¥To customize Bootstrap, create a file called src/custom.scss (or similar) and import the Bootstrap source stylesheet. Add any overrides before the imported file(s). You can reference Bootstrap's documentation for the names of the available variables.

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

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

注意:你可以使用 ~ 作为路径前缀,如上所示,以解析 node_modules 中的模块。

¥Note: You can prefix paths with ~, as displayed above, to resolve modules from node_modules.

最后,在 src/index.js 文件的开头导入新创建的 .scss 文件,而不是默认的 Bootstrap .css,例如:

¥Finally, import the newly created .scss file instead of the default Bootstrap .css in the beginning of your src/index.js file, for example:

import './custom.scss';