Javascript ReactJS::如何在页面更改时仅显示相关菜单项并隐藏其他菜单项

Javascript ReactJS::如何在页面更改时仅显示相关菜单项并隐藏其他菜单项,javascript,css,reactjs,events,navigation,Javascript,Css,Reactjs,Events,Navigation,我正在做一个在线全栈Web开发者训练营,刚刚被介绍来应对JS事件,在执行以下指令时遇到了一些困难: 菜单组件应仅显示相关项目。例如,如果 如果用户处于“店铺”页面,“店铺”菜单项不应再出现 展示 我曾尝试通过“activeClassName”和CSS方法执行此操作,但不幸的是,它没有被识别为DOM属性 我还尝试了以下指南和以前的堆栈溢出问题的答案,它们提供了如下解决方案: 不幸的是,到目前为止,我还没有取得任何成功,如果有人愿意提供帮助,我将不胜感激。学习如何在未来的项目中利用这一点将是非常棒的

我正在做一个在线全栈Web开发者训练营,刚刚被介绍来应对JS事件,在执行以下指令时遇到了一些困难:

菜单组件应仅显示相关项目。例如,如果 如果用户处于“店铺”页面,“店铺”菜单项不应再出现 展示

我曾尝试通过“activeClassName”和CSS方法执行此操作,但不幸的是,它没有被识别为DOM属性

我还尝试了以下指南和以前的堆栈溢出问题的答案,它们提供了如下解决方案:

不幸的是,到目前为止,我还没有取得任何成功,如果有人愿意提供帮助,我将不胜感激。学习如何在未来的项目中利用这一点将是非常棒的

我的代码如下:

Navigation.js

import React from 'react';
// Imported components from React Bootstrap.
import {Container, Col, Row, Navbar, Nav, NavLink, NavItem} from "react-bootstrap";

function Navigation() {
  return (
    <div>
      <Navbar id="navbar">

        <Container>
          <Row id="navrow">

            <Col id="navcol" className="d-none d-lg-flex">
              <Nav className="mrx-auto" navbar>

                <NavItem className="navitem">
                  <NavLink className="navlink" href="/Profile"><img src="./images/profile.png" alt="View Your Profile" title="View Your Profile" id="profileimg" /></NavLink>
                </NavItem>

                <NavItem className="navitem">
                  <NavLink className="navlink" href="/">HOME</NavLink>
                </NavItem>

                <NavItem className="navitem">
                  <NavLink className="navlink" href="/Shop">SHOP</NavLink>
                </NavItem>

              </Nav>
            </Col>

          </Row>
        </Container>

      </Navbar>
    </div>
  )
}

export default Navigation;
// Imported react libraries and components.
import React, { Component } from 'react';
// Imported css styles.
import './App.css';
// Imported components.
import Navigation from './components/Navigation';
import Header from './components/Header';
import Profile from './components/Profile';
import Landing from './components/Landing';
import Products from './components/Products';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
// Constructed a boolean value to determine whether a user is signed in or not. 
const loggedIn = true;
// Constructed a map array of objects to display the "Landing/ About Us" information. 
const landings =
  [{
    id: "1",
    landing_description: "We officially opened our doors June of 2020 and have created an environment that caters for anyone, no matter your fitness level. We pride ourselves in delivering professional services and providing top-performing equipment and facilities to our clients. Our mission is to create a healthier lifestyle for our staff, as well as for our customers. Our job is to provide you with a better quality life, whether it is upping your fitness levels or whether you want that body that you have been longing for."
  }];
// Constructed a map array of objects to display the products' information. 
const products =
  [{
    id: "2",
    product_name: "Classic Package",
    product_price: "R250.00 P/M",
    product_image: "./images/gym.jpg",
    product_description: "We have all of the equipment that is needed to enable anyone to achieve their ultimate goal. Our gym also have an indoor pool and a canteen for healthy refreshments and food items. Gain access to our facilities and start your transformation."
  },
  {
    id: "3",
    product_name: "Elite Package",
    product_price: "R350.00 P/M",
    product_image: "./images/spinning.jpg",
    product_description: "This membership plan gains you access to all of the equipment, as well as give you the option of joining up to two of our classes. Whether you are into spinning classes, yoga, aerobics, boxing or showing off your moves in a Zumba Fitness class."
  },
  {
    id: "4",
    product_name: "Pro Package",
    product_price: "R450.00 P/M",
    product_image: "./images/personal.jpg",
    product_description: "This membership plan grants you full access to all of our facilities and classes. In addition you also get assiged a personal trainer that will help you with your work-out plans, as well as meal plans. This is the ultimate package, which should give you your desired outcome at a faster pace."
  }];

console.log(typeof products);
// Rendering and returning data to be exported to Index.js.
class App extends Component {
  render() {
    return (
      <div>
        <BrowserRouter>
          <div className="App">
            {/* Included a link to the App.js stylesheet. */}
            <link
              rel="stylesheet"
              href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
              integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
              crossOrigin="anonymous"
            />
            <Navigation />
            {/* Added Header component. */}
            <Header name="Code Reviewer" loggedIn={loggedIn} />
            {/* Added Landing component. */}
            <Switch>
            <Route exact={true} path="/" render={() => (
              <Landing landings={landings} />
            )} />
            <Route path="/Profile" render={() => (
            <Profile />
            )} />
            {/* Added Products component. */}
            <Route path="/Shop" render={() => (
              <Products products={products} />
            )} />
            </Switch>
          </div>
        </BrowserRouter>
      </div>
    );
  }
}

// Exporting to render App component in Index.js where the ReactDom.Render() method is called.
export default App;
从“React”导入React;
//从React引导导入的组件。
从“react bootstrap”导入{容器、列、行、导航栏、导航、导航链接、导航项};
函数导航(){
返回(
家
商店
)
}
导出默认导航;
App.js

import React from 'react';
// Imported components from React Bootstrap.
import {Container, Col, Row, Navbar, Nav, NavLink, NavItem} from "react-bootstrap";

function Navigation() {
  return (
    <div>
      <Navbar id="navbar">

        <Container>
          <Row id="navrow">

            <Col id="navcol" className="d-none d-lg-flex">
              <Nav className="mrx-auto" navbar>

                <NavItem className="navitem">
                  <NavLink className="navlink" href="/Profile"><img src="./images/profile.png" alt="View Your Profile" title="View Your Profile" id="profileimg" /></NavLink>
                </NavItem>

                <NavItem className="navitem">
                  <NavLink className="navlink" href="/">HOME</NavLink>
                </NavItem>

                <NavItem className="navitem">
                  <NavLink className="navlink" href="/Shop">SHOP</NavLink>
                </NavItem>

              </Nav>
            </Col>

          </Row>
        </Container>

      </Navbar>
    </div>
  )
}

export default Navigation;
// Imported react libraries and components.
import React, { Component } from 'react';
// Imported css styles.
import './App.css';
// Imported components.
import Navigation from './components/Navigation';
import Header from './components/Header';
import Profile from './components/Profile';
import Landing from './components/Landing';
import Products from './components/Products';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
// Constructed a boolean value to determine whether a user is signed in or not. 
const loggedIn = true;
// Constructed a map array of objects to display the "Landing/ About Us" information. 
const landings =
  [{
    id: "1",
    landing_description: "We officially opened our doors June of 2020 and have created an environment that caters for anyone, no matter your fitness level. We pride ourselves in delivering professional services and providing top-performing equipment and facilities to our clients. Our mission is to create a healthier lifestyle for our staff, as well as for our customers. Our job is to provide you with a better quality life, whether it is upping your fitness levels or whether you want that body that you have been longing for."
  }];
// Constructed a map array of objects to display the products' information. 
const products =
  [{
    id: "2",
    product_name: "Classic Package",
    product_price: "R250.00 P/M",
    product_image: "./images/gym.jpg",
    product_description: "We have all of the equipment that is needed to enable anyone to achieve their ultimate goal. Our gym also have an indoor pool and a canteen for healthy refreshments and food items. Gain access to our facilities and start your transformation."
  },
  {
    id: "3",
    product_name: "Elite Package",
    product_price: "R350.00 P/M",
    product_image: "./images/spinning.jpg",
    product_description: "This membership plan gains you access to all of the equipment, as well as give you the option of joining up to two of our classes. Whether you are into spinning classes, yoga, aerobics, boxing or showing off your moves in a Zumba Fitness class."
  },
  {
    id: "4",
    product_name: "Pro Package",
    product_price: "R450.00 P/M",
    product_image: "./images/personal.jpg",
    product_description: "This membership plan grants you full access to all of our facilities and classes. In addition you also get assiged a personal trainer that will help you with your work-out plans, as well as meal plans. This is the ultimate package, which should give you your desired outcome at a faster pace."
  }];

console.log(typeof products);
// Rendering and returning data to be exported to Index.js.
class App extends Component {
  render() {
    return (
      <div>
        <BrowserRouter>
          <div className="App">
            {/* Included a link to the App.js stylesheet. */}
            <link
              rel="stylesheet"
              href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
              integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
              crossOrigin="anonymous"
            />
            <Navigation />
            {/* Added Header component. */}
            <Header name="Code Reviewer" loggedIn={loggedIn} />
            {/* Added Landing component. */}
            <Switch>
            <Route exact={true} path="/" render={() => (
              <Landing landings={landings} />
            )} />
            <Route path="/Profile" render={() => (
            <Profile />
            )} />
            {/* Added Products component. */}
            <Route path="/Shop" render={() => (
              <Products products={products} />
            )} />
            </Switch>
          </div>
        </BrowserRouter>
      </div>
    );
  }
}

// Exporting to render App component in Index.js where the ReactDom.Render() method is called.
export default App;
//导入的react库和组件。
从“React”导入React,{Component};
//导入的css样式。
导入“/App.css”;
//进口部件。
从“./components/Navigation”导入导航;
从“./components/Header”导入标题;
从“./components/Profile”导入配置文件;
从“./组件/平台”导入平台;
从“./组件/产品”进口产品;
从“react router dom”导入{BrowserRouter,Route,Switch};
//构造一个布尔值以确定用户是否已登录。
常数loggedIn=真;
//构建了一个对象的地图数组,以显示“着陆/关于我们”的信息。
常数着陆=
[{
id:“1”,
着陆装置说明:"我们于2020年6月正式开业,创造了一个适合任何人的环境,无论你的健康水平如何。我们以提供专业服务和为客户提供一流的设备和设施而自豪。我们的使命是为员工和客户创造更健康的生活方式。Our的工作是为你们提供更优质的生活,无论是提高你们的健康水平,还是你们想要你们一直渴望的身体。”
}];
//构建对象的地图数组以显示产品信息。
康斯特产品=
[{
id:“2”,
产品名称:“经典包装”,
产品价格:“R250.00 P/M”,
产品图片:“./images/gym.jpg”,
产品描述:“我们拥有使任何人都能实现其最终目标所需的所有设备。我们的健身房还有一个室内游泳池和一个食堂,提供健康的点心和食品。进入我们的设施,开始你的转型。”
},
{
id:“3”,
产品名称:“精英套餐”,
产品价格:“R350.00 P/M”,
产品图片:“./images/spining.jpg”,
产品描述:“此会员计划让您可以使用所有设备,并让您可以选择加入我们的两个课程。无论您是参加纺纱课程、瑜伽、健美操、拳击还是在尊巴健身课程中展示您的动作。”
},
{
id:“4”,
产品名称:“专业包装”,
产品价格:“450.00南非兰特/米”,
产品图片:“./images/personal.jpg”,
产品描述:“此会员计划允许您完全进入我们的所有设施和课程。此外,您还可以获得私人教练的帮助,帮助您制定健身计划和膳食计划。这是最终套餐,应该能以更快的速度为您提供所需的结果。”
}];
控制台日志(产品类型);
//呈现并返回要导出到Index.js的数据。
类应用程序扩展组件{
render(){
返回(
{/*包含指向App.js样式表的链接。*/}
{/*添加了头组件。*/}
{/*添加了着陆组件。*/}
(
)} />
(
)} />
{/*已添加产品组件。*/}
(
)} />
);
}
}
//导出到Index.js中调用ReactDom.render()方法的render App组件。
导出默认应用程序;
如果需要更多信息,请务必告诉我。

简单

导航组件上,导入
useLocation

import { useLocation } from 'react-router-dom';
添加
location
变量和
isCurrentURL
函数

isCurrentURL
函数将确定菜单的URL是否为当前URL

const location = useLocation();

const isCurrentURL = (url) => {
    return location.pathname.toLowerCase() === url.toLowerCase();
}
现在将所有
NavItem
包装如下:

{ !isCurrentURL('/Profile') ? <NavItem className="navitem">
                    <NavLink className="navlink" href="/Profile"><img src="./images/profile.png" alt="View Your Profile" title="View Your Profile" id="profileimg" /></NavLink>
                  </NavItem> : null }
{!isCurrentURL('/Profile')?
:null}
或者,您可以将菜单存储在一个数组中,然后进行迭代和检查


就是这样。因此,当前URL链接将不会呈现。

创建另一个名为history.js的文件

从“历史记录”导入CreateBrowserHistory

创建函数/箭头函数

const History = () => {
    return CreateBrowserHistory() }

export default History;


Then import history for 'history.js'; history.location[-1],

然后是历史,然后是一个自定义URL,其状态类似于useContext,它将向您显示过去的URL,并允许您在组件和不同文件的嵌套类或函数中严格重定向用户。

非常感谢。这非常有效。不客气。非常感谢您的帮助。非常感谢。