首页 > 解决方案 > 如何在 ReactJS 的三元运算符中使用 OR 条件

问题描述

我是 ReactJS 的新手。实际上,我正在研究 ReactJS 项目中的 Menues。在这里,我已经实现了活动菜单的逻辑例如,如果用户在第 2 页,它将显示 User 的活动菜单。目前,我使用window.location.pathname比较用户页面,但我想要两者。我的意思是,如果用户单击菜单,我会将其与状态值进行比较,或者如果用户在页面上,我会将其与window.location.pathname. 我是 ReactJS 的新手,请专家帮助我。如果有人不完全理解我的问题陈述,我也会提供代码。对不起,如果我因为不是母语而在英语语法上犯了错误。谢谢

代码

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

    this.state = {
      Item: 5,
      skip: 0
    }

    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }

  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div>
        <a href={this.urlParams()}>Example link</a>
        <pre>{this.urlParams()}</pre>
        <button onClick={this.handleClick}>Change link</button>
      </div>
    )
  }
}


ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))

标签: javascriptreactjsecmascript-6react-redux

解决方案


使用一个名为的状态activeMenu会不必要地使您的组件复杂化。您应该考虑通过以下方式对其进行简化:

import React, { Component } from 'react';
import { NavLink, withRouter } from 'react-router-dom';
import { Icon } from 'semantic-ui-react';
import Header from '../header/header';


// Style Components
import {LeftMenuStyle} from '../appStyles/appStyles'


class LeftMenuList extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const menus = [
      {
        name: 'dashboard',
        icon: 'dashboard',
      },
      {
        name: 'organizations',
        icon: 'sitemap',
      },
      {
        name: 'contacts',
        icon: 'phone square',
    },

      {
        name: 'products',
        icon: 'shopping cart',
      },
      {
        name: 'sales',
        icon: 'credit card',
      },
      {
        name: 'purchases',
        icon: 'shopping bag',
      },
      {
        name: 'shipments',
        icon: 'shipping',
      },
      {
        name: 'everything',
        icon: 'ald',
      },
      {
        name: 'reports',
        icon: 'chart line',
      },
      {
        name: 'logout',
        icon: 'arrow right',
      }

    ];

    return (
      <div>
        <Header />
        <LeftMenuStyle>
        <div className="left-menus">
          {menus.map(item => {
              return (
                <NavLink to={"/"+item.name} name={item.name} key={item.name}
                  className='menu'
                  activeClassName='active'
                  >
                  <Icon name={item.icon} size="large"/>
                  <span>{item.name}</span>
                </NavLink>
              )
          })}
        </div>
        </LeftMenuStyle>
      </div>
    );
  }
}

export default withRouter(LeftMenuList);

Link组件 from会自动将react-router-dom您的路径更改为活动路径,因此您的活动链接将获取active类名。

在这里你看到我们用一个WithRouter函数包装了组件,这为你提供了react-router特定的路径对象,你可以使用它来确定你的当前路径。


推荐阅读