在React中单击元素时修改className

时间:2018-11-21 10:06:09

标签: javascript reactjs

我在ReactJS中创建了一个菜单栏,它具有一些基本的路由功能。该组件的JSX如下:

class TopBar extends Component {
  state = {
    menus: [{id:0,menu:"Home"}, {id:1,menu:"Contact"}, {id:2,menu:"About"}]
  }
  addClass = e => {
    console.log("Addclass "+ e.target);
  }
  render() {
    return (
      <Router>
                <div>  
                    <nav class="navbar navbar-expand-lg">
                      <div class="row">
                        <div class="col-sm-12">
                          <div class="collapse navbar-collapse">
                            <ul class="navbar-nav mr-auto">
                              {this.state.menus.map((menu,index) =>
                                    <li className="nav-item ng-star-inserted">
                                      <a className={`nav-link ${'active'}`} id={"sample"+ menu.id} onClick={this.addClass} > 
                                        <Link to={menu.menu}> {menu.menu} </Link>
                                      </a>
                                    </li>
                                )}
                            </ul>
                          </div>
                        </div>
                      </div>
                    </nav>

          <Route path="/home" exact component={
            Home
          } />
          <Route path="/contact" exact component={
           Contact
          } />
          <Route path="/about" exact component={
            About
          } />
        </div>
      </Router>
    );
  }
}

CSS:

.navbar .nav-link.active {
    border-bottom: 3px solid #fdd92d;
}

当我单击特定菜单(主页/联系人/关于)时,我想将active类附加到该特定菜单。我添加了onClick事件,并尝试将id属性传递给它。
但是id在调试器中为空白。 enter image description here

点击菜单后,如何添加active className?

3 个答案:

答案 0 :(得分:0)

最好使用react-router-dom的NavLink来代替。

<NavLink to={menu.menu} activeClassName='active' className='nav-link'>
  {menu.menu}
</NavLink>

https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/NavLink.md

答案 1 :(得分:0)

以下是供您参考的示例

import * as React from "react";

import { NavLink } from "react-router-dom";
import  styles from "./NavigationMenu.css";

 function NavigationMenu() {
    return (
      <React.Fragment>
       <ul className={styles.nav}>
         <li>
          <NavLink to="/home" activeClassName={styles.active}>
             Home
          </NavLink>
        </li>
        <li>
         <NavLink to="/contacts" activeClassName={styles.active}>
            Contacts
         </NavLink>
        </li>
       <li>
         <NavLink to="/about" activeClassName={styles.active}>
           About
         </NavLink>
        </li>
      </ul>
   </React.Fragment>
  );
}

export default NavigationMenu;

只需在CSS文件中添加.active类,或者如果要对其进行重构,则可以按如下所示创建NavigationItem组件

import React from 'react';
import { NavLink } from 'react-router-dom';

import classes from './NavigationItem.css';

const navigationItem = ( props ) => (
   <li className={classes.NavigationItem}>
    <NavLink 
        to={props.link}
        exact={props.exact}
        activeClassName={classes.active}>{props.children}</NavLink>
  </li>
);

export default navigationItem;

<NavLink>会自动将活动类添加到当前活动链接或页面中

答案 2 :(得分:0)

要使其按照自己的方式工作,必须为每个菜单对象存储isActive键。您的addClass()函数应如下所示:

addClass = e => {
  this.setState({
    menus: this.state.menus.map(menu => ({
      ...menu,
      isActive: e.target.id == menu.id
    }))
  })
}

每次调用addClass时,我们都会遍历每个菜单对象,如果菜单的ID与用户单击的ID相匹配,则将其赋予isActive: true,否则将其设置为false。当然,我们不能使用.map来返回一组新菜单,因为我们不能直接对this.state.menus进行突变。

然后,我们可以通过检查菜单上的isActive键来检查菜单是否处于活动状态:

{
  this.state.menus.map(menu =>
    <a
      className={`nav ${menu.isActive ? 'active' : ''}`}
      id={menu.id}
      onClick={this.addClass}
    >
      {menu.menu}
    </a>
  )
}

为您构建此工作片段:

class Hello extends React.Component {
  state = {
    menus: [{id:0,menu:"Home"}, {id:1,menu:"Contact"}, {id:2,menu:"About"}]
  }

  addClass = e => {
    this.setState({
      menus: this.state.menus.map(menu => ({
        ...menu,
        isActive: e.target.id == menu.id
      }))
    })
  }

  render() {
    return (
      <div>
        {
          this.state.menus.map(menu =>
            <a
              style={{color: menu.isActive ? 'red' : 'black'}}
              className={`nav ${menu.isActive ? 'active' : ''}`}
              id={menu.id}
              onClick={this.addClass}
            >
              {menu.menu}
            </a>
          )
        }
      </div>
    )
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
</div>