在 React 中根据路由更改背景图像

Changing background Image based on Route in React

嘿,我有主页组件的背景图片。我已经将背景图像放在页眉组件中。在我的 Header 组件中有一个导航栏和背景图像。我将 Header 组件放在 React Router 内部的 switch 之外,以便某些页面可以访问导航栏。现在我想做的是,当我转到食物描述页面时,我想保留导航栏,但我想 change/remove 背景图像。我怎样才能做到这一点?

App.js

function App() {
  return (
    <div>
      <DataContextProvider>
        <LoginContextProvider>
          <Router>
            <Header></Header>
            <Switch>
              <Route exact path="/" component={Home} />
              <Route path="/login" component={Login} />
              <Route path="/food/:id" component={FoodDetail} />
            </Switch>
          </Router>
        </LoginContextProvider>
      </DataContextProvider>
    </div>
  );
}

Header.js

<div className={classes.grow}>
      <AppBar position="fixed" style={{ backgroundColor: "white" }}>
        <Container>
          <Toolbar>
            <Link to="/">
              <Typography className={classes.title} variant="h6" noWrap>
                Material-UI
              </Typography>
            </Link>

            <div className={classes.grow} />
            <div className={classes.sectionDesktop}>
              {loggedInUser.email ? (
                <MenuItem onClick={handleProfileMenuOpen}>
                  <IconButton
                    aria-label="account of current user"
                    aria-controls="primary-search-account-menu"
                    aria-haspopup="true"
                    color="inherit"
                  >
                    <AccountCircleIcon style={{ fill: "black" }} />
                  </IconButton>
                  <p className={classes.textColor}>{loggedInUser.name}</p>
                </MenuItem>
              ) : (
                <MenuItem onClick={handleLogin}>
                  <IconButton
                    aria-label="account of current user"
                    aria-controls="primary-search-account-menu"
                    aria-haspopup="true"
                    color="inherit"
                  >
                    <AccountCircleIcon style={{ fill: "black" }} />
                  </IconButton>
                  <p className={classes.textColor}>Login</p>
                </MenuItem>
              )}

              <IconButton
                aria-label="show 11 new notifications"
                color="inherit"
              >
                <Badge badgeContent={0} color="secondary">
                  <ShoppingCart style={{ fill: "black" }}></ShoppingCart>
                </Badge>
              </IconButton>
            </div>
            <div className={classes.sectionMobile}>
              <IconButton
                aria-label="show more"
                aria-controls={mobileMenuId}
                aria-haspopup="true"
                onClick={handleMobileMenuOpen}
                color="inherit"
              >
                <MenuIcon style={{ fill: "black" }} />
              </IconButton>
            </div>
          </Toolbar>
        </Container>
      </AppBar>
      {renderMobileMenu}

      {renderMenu}
      <div style={{ backgroundImage: `url(${bg})` }} className="header">
        <h2>Whatever you need, we will deliver it to you!</h2>
        <Paper component="form" className="search">
          <InputBase
            className={classes.input}
            placeholder="Search Keywords"
            inputProps={{ "aria-label": "search google maps" }}
            onChange={(e) => setSearch(e.target.value)}
          />
          <IconButton
            type="submit"
            className={classes.iconButton}
            aria-label="search"
          >
            <SearchIcon />
          </IconButton>
        </Paper>
      </div>
    </div>
  );
};

FoodDetail.js

const FoodDetail = () => {
  const { id } = useParams();
  const [foodDetails, setFoodDetails] = useState({});
  useEffect(() => {
    fetch(`http://localhost:5000/api/foods/${id}`)
      .then((res) => res.json())
      .then((data) => {
        setFoodDetails(data);
        console.log(data);
      });
  }, [id]);
  return (
    <div>
      <h1>Details</h1>
      <h1>Name: {foodDetails.name} </h1>
    </div>
  );
};

您需要使用'useLocation'获取页面路径,然后将其添加到className中。

Header.js

import React from "react";
import { useLocation } from "react-router-dom";
import "./Header.css";

import Navigation from "../Navigation/Navigation";

export default function Header() {
  const path = useLocation().pathname;
  const location = path.split("/")[1];

  return (
    <div className={"header " + location}>
      <Navigation />
    </div>
  );
}

Header.css

.header {
  height: 300px;
}
.header.home {
  background: grey
}
.header.about {
  background: red
}
.header.contact {
  background: yellow
}

查看我的完整演示 : Stackblitz