javascript - 如何在 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' ))
解决方案
使用一个名为的状态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
特定的路径对象,你可以使用它来确定你的当前路径。
推荐阅读
- networking - 使用端到端寻址
- flutter - flutter lint 参数类型规则用法
- matlab - 用 numpy.random 重现 Matlab 的 randi 的伪随机数
- javascript - React Docker 映像在本地机器上工作,但是当我将它移动到服务器时会出现 Hooks 错误
- javascript - 在 JavaScript 中按日期或布尔值对 JSON 对象数组进行排序
- laravel - spatie/laravel-short-schedule 如何在 cron 中使用它?
- python - 用python自动化java相关的东西:
- talend - 将 sql 查询转换为 talend 作业
- django - Django 模型保存方法
- javascript - 为什么在 Firefox 中显示 OK 但在 Chrome 和 Safari 中显示的变量显示 NaN?