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

ReactJS :: How to Show Only Relevant Menu Items and Hide Other Menu Items Upon Page Change

我正在参加在线全栈 Web 开发人员训练营,刚刚接触 React JS 事件,但在执行以下说明时遇到了一些困难:

The menu component should only display relevant items. For example, if the user is on the “shop” page, the “shop” menu item should no longer be displayed.

我已经尝试通过“activeClassName”和 CSS 方法执行此操作,但不幸的是,这未被识别为 DOM 属性.

我也尝试过遵循指南和以前的 Stack Overflow 问题的答案,这些问题提供了如下解决方案:https://www.pluralsight.com/guides/how-to-show-and-hide-reactjs-components

不幸的是,我还没有成功,如果有人愿意提供任何帮助,我将不胜感激。学习如何在未来的项目中使用它会很棒。

我的代码如下:

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;

App.js

// 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;

如果需要任何进一步的信息,请告诉我。

简单。

在您的 Navigation 组件中,导入 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 }

或者,您可以将菜单存储在数组中,然后迭代并检查。

就是这样。所以,当前的URLlink不会被渲染。

创建另一个名为 history.js

的文件

从 'history'

导入 CreateBrowserHistory

创建一个 function/arrow 函数

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

export default History;


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

然后是历史,然后你有一个自定义的 URL 和像 useContext 这样的状态,它将向你显示 URL 过去的那些,并允许你在嵌套的 类 或函数中严厉地重定向用户组件和不同的文件。