将Bootstrap与React集成:开发人员指南

松和璧
2023-12-01

Integrating Bootstrap with React allows React developers to use Bootstrap’s state-of-the-art grid system and its various other components.

通过将Bootstrap与React集成,React开发人员可以使用Bootstrap的最新网格系统及其各种其他组件。

In this tutorial, we’re going to:

在本教程中,我们将要:

  • explore tools and techniques for building a user interface with Bootstrap’s look and feel for a React-powered web application

    探索用于构建基于Reacts驱动的Web应用程序的Bootstrap外观的用户界面的工具和技术
  • use reactstrap to build a React contact list application.

    使用reactstrap构建一个React联系人列表应用程序。

React is one of the most popular JavaScript technologies for interactive web applications. Its popularity derives from its component-based modular approach, composability and fast re-rendering algorithm.

React是用于交互式Web应用程序的最受欢迎JavaScript技术之一。 它的流行源自其基于组件的模块化方法,可组合性和快速重新渲染算法。

However, being a view library, React doesn’t have any built-in mechanism that can help us create designs that are responsive, sleek and intuitive. That’s where a front-end design framework like Bootstrap steps in.

但是,作为视图库,React没有任何内置机制可以帮助我们创建响应式,时尚且直观的设计。 这就是像Bootstrap这样的前端设计框架的所在。

为什么不能在React中仅包含Bootstrap组件 (Why You Can’t Just Include Bootstrap Components with React)

Combining Bootstrap with React isn’t as easy as adding <link rel="stylesheet" /> to an index.html file. This is because Bootstrap depends on jQuery for powering certain UI components. jQuery uses a direct DOM manipulation approach that’s contradictory to React’s declarative approach.

将Bootstrap与React结合起来并不像将<link rel="stylesheet" />index.html文件那样容易。 这是因为Bootstrap依靠jQuery为某些UI组件提供动力。 jQuery使用直接的DOM操作方法,这与React的声明方法相矛盾。

If we need Bootstrap just for the responsive 12 column grid, or the components that don’t use jQuery, we can simply resort to the vanilla Bootstrap stylesheet. Otherwise, there are many libraries that take care of bridging the gap between React and Bootstrap. We’ll compare both methods so that we’ll be in a better position to choose the approach that works for our specific case.

如果我们仅需要响应式12列网格的Bootstrap或不使用jQuery的组件,则可以简单地使用原始的Bootstrap样式表。 否则,有许多库需要弥合React和Bootstrap之间的鸿沟。 我们将比较这两种方法,以便更好地选择适合于特定情况的方法。

Let’s get started!

让我们开始吧!

使用React设置Bootstrap样式表 (Setting up a Bootstrap Stylesheet with React)

Let’s use the Create React App CLI to create a React project, which requires zero configuration to get started.

让我们使用Create React App CLI创建一个React项目,该项目需要零配置才能开始。

We install Create React App and run the following command to start a new project and serve the development build:

我们安装Create React App并运行以下命令以启动一个新项目并为开发构建提供服务:

$ create-react-app react-and-bootstrap
$ cd react-and-bootstrap
$ npm start

Here’s the directory structure created by Create React App:

这是由Create React App创建的目录结构:

.
├── package.json
├── public
│   ├── favicon.ico
│   ├── index.html
│   └── manifest.json
├── README.md
├── src
│   ├── App.css
│   ├── App.js
│   ├── App.test.js
│   ├── index.css
│   ├── index.js
│   ├── logo.svg
│   └── registerServiceWorker.js
└── yarn.lock

Next, let’s download the latest version of the Bootstrap library from Bootstrap’s official site. The package includes both the compiled and minified versions of the CSS and JavaScript. We’ll just copy the CSS and place it inside the public/ directory. For projects that just need the grid, there is a grid-specific stylesheet included too.

接下来,让我们从Bootstrap的官方站点下载最新版本的Bootstrap库。 该软件包包括CSS和JavaScript的编译版本和缩小版本。 我们将只复制CSS并将其放置在public/目录中。 对于只需要网格的项目,也包括特定于网格的样式表。

Next, we create a new directory for css inside public/, paste bootstrap.min.css in our newly created css directory, and link it from public/index.html:

接下来,我们在public/内为css创建一个新目录,将bootstrap.min.css粘贴到新创建的css目录中,并从public/index.html链接:

<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>

Alternatively, we can use a CDN to fetch the minified CSS:

另外,我们可以使用CDN来获取缩小CSS:

<link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

Let’s have a look at what works and what doesn’t with this setup.

让我们看一下在此设置下什么有效,什么无效。

将Vanilla Bootstrap与React结合使用 (Using Vanilla Bootstrap with React)

Once we add the Bootstrap stylesheet to a React project, we can use the regular Bootstrap classes inside JSX code. Let’s head over to the Bootstrap demo site and copy over some random example code, just to check everything is working as it should:

将Bootstrap样式表添加到React项目后,我们可以在JSX代码中使用常规的Bootstrap类。 让我们转到Bootstrap演示站点并复制一些随机示例代码,只是检查一切是否正常:

As we can see, the form looks good, but the NavBar doesn’t. That’s because the NavBar depends on the Collapse jQuery plugin, which we haven’t imported. Apart from being unable to toggle navigation links, we can’t use features like dropdown menus, closable alerts and modal windows, to name a few.

如我们所见,该窗体看起来不错,但NavBar却没有。 这是因为NavBar依赖于我们尚未导入的Collapse jQuery插件 。 除了无法切换导航链接外,我们不能使用下拉菜单,可关闭的警报和模式窗口之类的功能。

Wouldn’t it be awesome if we could import Bootstrap as React components to make the most out of React? For instance, imagine if we could use a combination of Grid, Row and Column components to organize the page instead of the pesky HTML classes:

如果我们可以将Bootstrap导入为React组件以充分利用React会不会很棒? 例如,假设我们可以使用Grid,Row和Column组件的组合来组织页面而不是讨厌HTML类:

<!-- Bootstrap with HTML classes -->

<div class="container">
  <div class="row">
    <div class="col-sm">
      One of three columns
    </div>
    <div class="col-sm">
      One of three columns
    </div>
    <div class="col-sm">
      One of three columns
    </div>
  </div>
</div>

<!-- Bootstrap with React Components -->

<Grid>
  <Row>
      <Col sm>
        One of three columns
    </Col>
    <Col sm>
        One of three columns
    </Col>
     <Col sm>
        One of three columns
    </Col>
  </Row>
</Grid>

Fortunately, we don’t have to implement our own library to serve this purpose, as there are some popular solutions already available. Let’s take a look at some of them.

幸运的是,我们已经不必实现自己的库来实现此目的,因为已经有了一些流行的解决方案。 让我们看看其中的一些。

React和Bootstrap第三方库概述 (An Overview of Third-party Libraries for React and Bootstrap)

There are a few libraries that try to create a React-specific implementation of Bootstrap so that we can use JSX components while working with Bootstrap styles. I’ve compiled a list of a few popular Bootstrap modules that we can use with our React projects.

有一些库试图创建特定于React的Bootstrap实现,以便我们在使用Bootstrap样式时可以使用JSX组件。 我已经列出了一些可用于React项目的流行Bootstrap模块的列表。

React-Bootstrap is by far one of the most popular libraries for adding Bootstrap components into React. However, at the time of writing this tutorial, it targets Bootstrap v3 and not the latest version of Bootstrap. It’s in active development and the API might break when a newer version is released.

到目前为止, React-Bootstrap是将Bootstrap组件添加到React的最受欢迎的库之一。 但是,在编写本教程时,它针对的是Bootstrap v3,而不是最新版本的Bootstrap。 它正在积极开发中,发布较新版本时,API可能会中断。

reactstrap is another library that gives us the ability to use Bootstrap components in React. Unlike React-Bootstrap, reactstrap is built for the latest version of Bootstrap. The module includes components for typography, icons, forms, buttons, tables, layout grids, and navigation. It’s also in active development and it’s a nice alternative for building React-powered Bootstrap apps.

reactstrap是另一个库,使我们能够在React中使用Bootstrap组件。 与React-Bootstrap不同,reactstrap是为最新版本的Bootstrap构建的。 该模块包括印刷,图标,表单,按钮,表格,布局网格和导航的组件。 它也在积极开发中,是构建基于React的Bootstrap应用程序的不错选择。

There are a few other libraries like React-UI, and domain-specific modules like React-bootstrap-table and CoreUI-React Admin Panel on GitHub, which provide extended support for creating awesome UIs using React.

GitHub上还有其他一些库(如React-UI )和特定于域的模块(如React-bootstrap-tableCoreUI-React Admin Panel) ,它们提供了扩展支持,可使用React创建出色的UI。

The rest of this tutorial will focus on reactstrap, because it’s the only popular module that uses the latest version of Bootstrap.

本教程的其余部分将重点介绍reactstrap,因为它是唯一使用最新版本的Bootstrap的流行模块。

设置reactstrap库 (Setting up the reactstrap Library)

We start by installing the reactstrap library using npm:

我们首先使用npm安装reactstrap库:

npm install --save reactstrap@next

Now we can import the relevant components from the module as follows:

现在我们可以从模块中导入相关组件,如下所示:

import { Container, Row, Col} from 'reactstrap';

However, the library won’t work as we might expect it to yet. As explained on the reactstrap website, the reason for this is that reactstrap doesn’t include Bootstrap CSS, so we need to add it ourselves:

但是,该库将无法正常运行。 如reactstrap网站上所述,其原因是reactstrap不包含Bootstrap CSS,因此我们需要自己添加它:

npm install --save bootstrap

Next, we import Bootstrap CSS in the src/index.js file:

接下来,我们在src/index.js文件中导入Bootstrap CSS:

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

Bootstrap Grid基础 (Bootstrap Grid Basics)

Bootstrap has a responsive, mobile first and fluid grid system that allows up to 12 columns per page. To use the grid, we’ll need to import the Container, Row and Col components.

Bootstrap具有响应式,移动优先和流体网格系统 ,每页最多允许12列。 要使用网格,我们需要导入Container,Row和Col组件。

The Container accepts a fluid property that converts a fixed-width layout into a full-width layout. Essentially, it adds the corresponding .container-fluid Bootstrap class to the grid.

容器接受fluid属性,该属性会将固定宽度的布局转换为全角布局。 本质上,它将相应的.container-fluid Bootstrap类添加到网格。

As for <Col>s, we can configure them to accept props such as xs, md, sm and lg that are equivalent to Bootstrap’s col-* classes — for exmple, <Col xs="6"> </Col>

至于<Col> ,我们可以配置它们以接受与Bootstrap的col- col-*类等效的道具,例如xsmdsmlg ,例如<Col xs="6"> </Col>

Alternatively, we can pass an object to the props with optional properties like size, order and offset. The size property describes the number of columns, whereas order lets us order the columns and accepts a value from 1 to 12. The offset property moves the columns to the right.

或者,我们可以将对象传递给具有可选属性(例如sizeorderoffset的道具。 size属性描述列的数量,而order可让我们对列进行排序并接受1到12之间的值offset属性将列向右移动。

The code below demonstrates some of the Grid features in reactstrap:

下面的代码演示了reactstrap中的一些Grid功能:

React中的Bootstrap样式组件 (Bootstrap Style Components in React)

Now that we have reactstrap at our fingertips, there are tons of Bootstrap 4 components that we can use with React. Covering them all is beyond the scope of this tutorial, but let’s try a few important components and use them in an actual project — say, a contact list app.

现在我们已经触手可及了Reactstrap,我们可以在React中使用大量的Bootstrap 4组件。 涵盖所有内容超出了本教程的范围,但是让我们尝试一些重要的组件并在实际项目中使用它们-例如,联系人列表应用程序。

reactstrap Navbars are responsive navigation bar components. A Navbar can have subcomponents like NavbarBrand, Nav, NavItem, etc. for better organizing navigation links.

reactstrap导航栏是响应式导航栏组件。 导航栏可以具有NavbarBrand,Nav,NavItem等子组件,以便更好地组织导航链接。

To make the NavBar responsive, we can include a <NavbarToggler> inside our <Navbar> component and then wrap <NavItems> into a <Collapse> component.

为了使NavBar具有响应能力,我们可以在<Navbar>组件内包含<NavbarToggler> ,然后将<NavItems>包装到<Collapse>组件中。

Take a look at the code below, which shows how we can use the Navbar component and React state to store the toggle data:

看下面的代码,它显示了我们如何使用Navbar组件和React状态来存储切换数据:

export default class Example extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      isOpen: false
    };
  }
  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }
  render() {
    return (
      <div>
        <Navbar color="faded" light expand="md">
            {/* Brandname */}
               <NavbarBrand href="/">
                Demo
            </NavbarBrand>
               {/* Add toggler to auto-collapse */}
          <NavbarToggler onClick={this.toggle} />
          <Collapse isOpen={this.state.isOpen} navbar>

              {/*Pull left */}
            <Nav className="ml-auto" navbar>
                <NavItem>
                    <NavLink href="/link/">
                        Left Nav Link
                    </NavLink>
                </NavItem>
            </Nav>

            {/* Pull right */}
            <Nav className="mr-auto" navbar>
              <UncontrolledDropdown nav inNavbar>
                <DropdownToggle nav caret>
                  Bob
                </DropdownToggle>

                <DropdownMenu >
                  <DropdownItem>
                    Account
                  </DropdownItem>
                  <DropdownItem>
                    Settings
                  </DropdownItem>
                  <DropdownItem divider />
                  <DropdownItem>
                    Logout
                  </DropdownItem>
                </DropdownMenu>
              </UncontrolledDropdown>
            </Nav>
          </Collapse>
        </Navbar>
      </div>
    );
  }
}

The reactstrap Modal component creates a Bootstrap Modal with a header, a body, and a footer.

reactstrap Modal组件创建一个具有页眉,正文和页脚的Bootstrap Modal。

A modal component accepts a few props and callbacks to make the window interactive and closable.

模态组件接受一些道具和回调,以使窗口具有交互性和可关闭性。

The isOpen prop determines whether the modal should be visible. The toggle callback can be used to toggle the value of isOpen in the controlling component.

isOpen道具确定模态是否应可见。 toggle回调可用于在控制组件中切换isOpen的值。

There are additional props for adding transition effects. The callbacks available include onEnter, onExit, onOpened, and onClosed:

还有其他道具可以添加过渡效果。 可用的回调包括onEnteronExitonOpenedonClosed

{/*For the modal to open, this.state.show should become true which is usually triggered by an onClick event */}
{/* toggleModal would set state of show to false onClose*/}

<Modal isOpen={this.state.show} toggle={this.toggleModal} >

    <ModalHeader toggle={this.toggle}>
        Modal title
    </ModalHeader>

    <ModalBody>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </ModalBody>

    <ModalFooter>
        <Button color="primary" onClick={this.toggle}>Do Something</Button>{' '}
        <Button color="secondary" onClick={this.toggle}>Cancel</Button>
     </ModalFooter>
</Modal>

形式 (Forms)

A reactstrap <Form> can be either inline or horizontal.

reactstrap <Form>可以是inline水平

An Input component renders an <input> element. We can wrap multiple Input components into a FormGroup for state validation, proper spacing, and to access other FormGroup features.

Input组件呈现一个<input>元素。 我们可以将多个Input组件包装到FormGroup以进行状态验证,适当的间距以及访问其他FormGroup功能。

It’s always a good idea to set a label using <Label>. There’s a lot more to forms, and you should check out the Bootstrap documentation on Forms.

使用<Label>设置标签始终是一个好主意。 表单还有很多其他内容,您应该查看Forms上Bootstrap文档

Here’s the code for our reactstrap form:

这是我们的reactstrap表单的代码:

<Form>
   <FormGroup row>
      <Label for="exampleEmail" sm={2}>Email</Label>
      <Col sm={10}>
          <Input type="email" name="email" id="exampleEmail" placeholder="with a placeholder" />
      </Col>
   </FormGroup>

   <FormGroup row>
      <Label for="examplePassword" sm={2}>Password</Label>
      <Col sm={10}>
         <Input type="password" name="password" id="examplePassword" placeholder="password placeholder" />
      </Col>
   </FormGroup>

   <FormGroup row>
      <Label for="exampleSelect" sm={2}>Select</Label>
      <Col sm={10}>
          <Input type="select" name="select" id="exampleSelect" />
      </Col>
   </FormGroup>

   <FormGroup row>
      <Label for="exampleSelectMulti" sm={2}>Select Multiple</Label>
      <Col sm={10}>
        <Input type="select" name="selectMulti" id="exampleSelectMulti" multiple />
      </Col>
    </FormGroup>

  <FormGroup row>
    <Label for="exampleText" sm={2}>Text Area</Label>
    <Col sm={10}>
      <Input type="textarea" name="text" id="exampleText" />
    </Col>
  </FormGroup>
</Form>

列表组 (ListGroup)

The reactstrap ListGroup makes it easier to style and control list items in React. The ListGroup wraps ListGroupItems, which can be made interactive using the onClick callback.

reactstrap ListGroup使在React中更轻松地设置样式和控制列表项。 ListGroup包装ListGroupItems ,可以使用onClick回调使其具有交互性。

Here’s what the code looks like:

代码如下所示:

<ListGroup>
  <ListGroupItem>Item 1</ListGroupItem>
  <ListGroupItem>Item 2</ListGroupItem>
  <ListGroupItem>...</ListGroupItem>
</ListGroup>;

纽扣 (Buttons)

Buttons are an integral part of any design framework. For buttons, there’s a reactstrap <Button> component. Apart from the active and disabled properties, we can use color and size to set the button’s style (primary, success, etc.) and size (‘lg’, ‘sm’, etc.):

按钮是任何设计框架的组成部分。 对于按钮,有一个reactstrap <Button>组件 。 除了activedisabled属性,我们还可以使用colorsize来设置按钮的样式(主要,成功等)和大小(“ lg”,“ sm”等):

{/*ButtonToolbar helps to organize buttons */}

 <div>
    <Button color="primary">primary</Button>{' '}

    <Button color="secondary">secondary</Button>{' '}

    <Button color="success">success</Button>{' '}

    <Button color="info">info</Button>{' '}

    <Button color="warning">warning</Button>{' '}

    <Button color="danger">danger</Button>{' '}

    <Button color="link">link</Button>
 </div>

演示:带有reactstrap的联系人列表应用程序UI (Demo: A Contact List Application UI with reactstrap)

Here’s a sample demo built using the components discussed in this tutorial.

这是一个使用本教程中讨论的组件构建的示例演示。

Check it out and experiment with it to familiarize yourself with reactstrap:

进行检查并尝试一下,以使自己熟悉reactstrap:

摘要 (Summary)

We’ve now covered everything you need to know to make the best of Bootstrap with React.

现在,我们已经涵盖了使用React充分利用Bootstrap所需的所有知识。

There’s no shortage of libraries for integrating Bootstrap with React, and we’ve looked at some of the most popular options. We also explored a popular library called reactstrap. If you’re ever in doubt, don’t forget to check the documentation page to know more about the available components.

不难将Bootstrap与React集成在一起的库,我们已经研究了一些最受欢迎的选项。 我们还探索了一个流行的库,称为reactstrap。 如果您有任何疑问,请不要忘记查看文档页面以了解有关可用组件的更多信息。

So, what are your thoughts about building responsive UIs using Bootstrap with React? If you have any suggestions about Bootstrap in general or a particular library that you’ve found useful, please feel free to share it through the comments.

那么,您对使用带有Bootstrap和React的响应式UI的想法是什么? 如果您对一般的Bootstrap或发现有用的特定库有任何建议,请随时通过评论分享。

If you’ve got the basics of Bootstrap under your belt but are wondering how to take your Bootstrap skills to the next level, check out our Building Your First Website with Bootstrap 4 course for a quick and fun introduction to the power of Bootstrap.

如果您掌握了Bootstrap的基础知识,但又想知道如何将Bootstrap技能提高到一个新的水平,请查看我们的使用Bootstrap 4建立您的第一个网站课程,以快速,有趣地介绍Bootstrap的功能。

翻译自: https://www.sitepoint.com/integrating-bootstrap-with-react/

 类似资料: