首页 > 解决方案 > 如何使用 react-router 创建侧边栏并设置按钮样式

问题描述

我想创建一个带有按钮的侧边栏,如图所示。我想让按钮在它处于活动状态时变为深灰色。我有引导代码,但是如果我使用 public/index.html 中的 css 文件和 javascript 文件应用引导,那么导航栏图像会出现在导航栏的中间,所以我想将 react-bootstrap 用于我的侧边栏。

https://i.stack.imgur.com/DjNGy.jpg

这是引导代码。如何使用反应路由器的链接而不是标签?对于反应引导,我们通常使用 <'Row'> <'Col'> 那么我们如何使用这些许多“col”类“col-sm-2 col-md-2 col-lg-2 col-xl-2”。我也对 react-bootstrap 中的 ul 标签感到困惑,如何将它们与导航药丸和其他类一起使用

<nav class="d-none d-md-block col-sm-2 col-md-2 col-lg-2 col-xl-2 sidebar">    
        <div class="sidebar-sticky">
                <ul class="nav nav-pills  nav-fill flex-column" role="tablist" style="margin-top:42px;">
                        <li class="nav-item">
                          <a class="nav-link active" data-toggle="pill" href="#/!" style="text-align:left;">
                            <img src="/images/windows.png" style="height:20px;">
                            Dashboard</a>
                        </li>
                        <li class="nav-item">
                          <a class="nav-link" data-toggle="pill" href="#!people" style="text-align:left;">
                                <img src="/images/people.png" style="height:20px;">                                
                            People</a>
                        </li>
                </ul>
        </div>
      </nav>

侧边栏的 css

.sidebar {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    z-index: 100;
    padding: 48px 0 0;
}

标签: javascriptcssreactjstwitter-bootstrap

解决方案


您可以使用它通过“Link”反应路由器标签替换您的“a”标签。

例如

<Link to="/target" />

或者

<Link to="/target">
  <!-- your tags come here --> 
</Link>

但是你应该避免在 index.html 中使用 css 和 js 文件。正确的方法是创建一个新组件并在其自己的范围内设置样式。

当您使用 react-bootstrap 时,您可以像这样创建组件(对于您的情况,我认为没有必要使用许多 css 类。您可以通过默认的 react-bootstrap 列实现您的目标):

<Container> // Your sidebar
  <Row>
    <Col><Link to="/path-1" /></Col>
  </Row>
  <Row>
    <Col><Link to="/path-2" /></Col>
  </Row>
  <Row>
    <Col><Link to="/path-2" /></Col>
  </Row>
</Container>

您需要应用一些 css 样式来实现最终布局。


推荐阅读