条件渲染反应路由器域

问题描述 投票:0回答:1

我正在制作一个广告网站,其中包含可重复使用的组件,这些组件会根据页面的不同而加载不同的图形。我正在使用react-router-dom路由确切路径。我想我需要能够使用useEffect,[]读取状态。因此,我该如何传递状态,以便组件可以读取它。

请注意,英雄部分会出现在家庭,顾问和解决方案的功能中


const Hero = props => {
 useEffect(() => {
  console.log(props);
 }, []);
 return (
  <Fragment>
   <div className='grid-hero'>
    <Fragment>
     <div className='overlay'>
      <div>
       <p className='bg-dark'></p>
       <img src={{ homeimg } || { consimg } || { solsimg }} alt='' />
      </div>
     </div>
    </Fragment>
  <Router>
   <Fragment>
    <Navbar />

    <Switch>
     <Route exact path='/' component={Home} />
     <Route exact path='/consultants' component={Consultants} />
     <Route exact path='/solutions' component={Solutions} />
     <Route exact path='/contactus' component={ContactUs} />"
    </Switch>
   </Fragment>
  </Router>
    <div
    className={
     {pathname === "/" && ("grid-home")}
     {pathname === "/consultants" && ("grid-consultants")}
     {pathname === "/solutions" && ("grid-solutions")}
    }>
javascript reactjs react-router-dom
1个回答
0
投票

也许这就是您想要的:

我已将Hero添加为您可以在其中切换图片的顶级图片组件。我没有图像,所以我使用了字符串,但是如果您导入像JSX这样的图像,则可以通过删除Hero虚拟组件中的img字符串来使用此代码。

添加参考图像导入语法以获取帮助:

import img from './img.png';

完整示例:

import React, { Fragment } from "react";
import {
  BrowserRouter as Router,
  Route,
  Link,
  useLocation
} from "react-router-dom";

function BasicExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/contactus">ContactUs</Link>
          </li>
          <li>
            <Link to="/solutions">Solutions</Link>
          </li>
        </ul>

        <hr />
        <Hero />
        <Route exact path="/" component={Home} />
        <Route path="/contactus" component={ContactUs} />
        <Route path="/solutions" component={Solutions} />
      </div>
    </Router>
  );
}

const Hero = () => {
  const homeimg = "HOME_IMAGE";
  const consimg = "CONTACT_US_IMAGE";
  const solsimg = "SOLUTIONS_IMAGE";
  let img = null;

  const location = useLocation();
  if (location.pathname === "/") img = homeimg;
  else if (location.pathname === "/contactus") img = consimg;
  else if (location.pathname === "/solutions") img = solsimg;

  return (
    <Fragment>
      <h3>{location.pathname}</h3>
      <div className="grid-hero">
        <Fragment>
          <div className="overlay">
            <div>
              <p className="bg-dark" />
              {img}
            </div>
          </div>
        </Fragment>
      </div>
    </Fragment>
  );
};

function Home() {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

function ContactUs() {
  return (
    <div>
      <h2>ContactUs</h2>
    </div>
  );
}

function Solutions() {
  return (
    <div>
      <h2>Solutions</h2>
    </div>
  );
}

export default BasicExample;

codepen-link

© www.soinside.com 2019 - 2024. All rights reserved.