ReactJS Bootstrap入门教程与实例 | reactstrap教程

1,188 阅读2分钟

在这篇博文中,我们将探讨如何将bootstrap框架与ReactJS库整合

React bootstrap组件

Bootstrap是一个流行的开源HTML、Javascript和CSS框架,用于构建针对桌面和移动的响应式应用程序。Bootstrap是基于JQuery框架开发的。在本教程中,我们将学习在没有JQuery的情况下将Bootstrap整合到react库中。由于Bootstrap是基于Jquery库的,所以很难与React库集成。

有许多npm项目可以作为npm包,我们可以很容易地集成到react中。

npm包的好处是我们可以使用经过测试的现成的网格和其他Bootstrap UI组件。

我们将选择reactstrap npm 包,因为它使用 bootstrap 的最新版本,并且经常更新。

前提条件

安装Node和npm命令首先,确保在你的操作系统上安装nodejs环境。安装完毕后,请发出以下命令来检查node和npm命令是否工作

B:\Workspace\blog\reactapp\helloworldreact>node --version
v8.10.0

B:\Workspace\blog\reactapp\helloworldreact>npm --version
5.6.0

如果命令给出了版本号,说明它已经正确安装了 下面的章节解释了

  • 使用React Bootstrap集成的例子
  • React Bootstrap按钮组件示例

首先使用create-react-app cli工具创建reactJS应用程序。 reactstrap需要依赖bootstrap npm库。使用npm或yarn命令行在你的应用程序中安装这两个依赖项。

npm install --save bootstrap reactstrap
yarn add bootstrap reactstrap

一旦依赖关系安装完毕,就会在应用程序的node_modules文件夹中添加bootstrap和reactstrap文件夹,同时也会在package.json的依赖关系部分添加一个条目 这里是我的package.json文件

{
  "name": "helloworldreact",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "^4.1.3",
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-scripts": "2.0.5",
    "reactstrap": "^6.5.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "devDependencies": {
    "uuid": "^3.3.2"
  }
}

这就在应用程序中安装了所需的依赖项

导入 reactstrap 组件和 bootstrap CSS 文件

reactstrap以组件的形式提供每个UI元素。在app/index.js中导入bootstrap.css

import 'bootstrap/dist/css/bootstrap.css';

在应用程序中导入按钮组件 - app/app.js

import { Button } from 'reactstrap';

按钮组件的例子



import React, { Component } from 'react';
import './App.css';
import { Button } from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.css';

class App extends Component {
  render() {
    return (
      
        
        primary Button{' '}
        secondary Button {' '}
        success Button{' '}
        info Button{' '}
        warning Button{' '}
        danger Buton{' '}
      
      
    );
  }
}

export default App;

使用npm start命令启动react开发服务器,以下是按钮输出的屏幕截图

react bootstrap button example