我希望根据元素的前一个同级是否具有特定的className来有条件地呈现该元素。
当用户位于页面上该Nav.Link上的href="“位置时,Nav.Link会收到" is -active”的(这是由第三方库实现的)。
我希望根据Nav.Link的className是否为"is-active“,在其父Nav.Item内的Nav.Link之后呈现一个Coin元素。
我不知道该怎么做。
import React, { Component } from "react";
import Nav from "react-bootstrap/Nav";
import "./lrg-nav.styles.scss";
import { Row, Col } from "react-bootstrap";
import ScrollspyNav from "react-scrollspy-nav";
import Coin from "./coin-spinner/coin-spinner.component";
class LrgNav extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<Row className="lrg-nav-container">
<Col className="d-flex align-items-center justify-content-center">
<ScrollspyNav
scrollTargetIds={["about-me", "work", "skills"]}
activeNavClass="is-active"
scrollDuration="1000"
headerBackground="true"
>
<Nav>
<Nav.Item className="d-flex align-items-center">
<Nav.Link
className="about-me is-active lrgNavItem pl-4 pr-0"
href="#about-me"
>
About Me
</Nav.Link>
{/* this is where I'd like to render a <Coin/> element based on if the previous sibling <Nav.Link className="is-active"> is true */}
</Nav.Item>
<Nav.Item className="d-flex align-items-center">
<Nav.Link className="lrgNavItem pl-4 pr-0" href="#work">
Work
</Nav.Link>
{/* this is where I'd like to render a <Coin/> element based on if the previous sibling <Nav.Link className="is-active"> is true */}
</Nav.Item>
<Nav.Item className="d-flex align-items-center">
<Nav.Link className="lrgNavItem pl-4 pr-0" href="#skills">
Skills
</Nav.Link>
{/* this is where I'd like to render a <Coin/> element based on if the previous sibling <Nav.Link className="is-active"> is true */}
</Nav.Item>
<Nav.Item className="d-flex align-items-center">
<Nav.Link className="lrgNavItem pl-4 pr-0" href="#aFewWords">
A Few Words
</Nav.Link>
{/* this is where I'd like to render a <Coin/> element based on if the previous sibling <Nav.Link className="is-active"> is true */}
</Nav.Item>
<Nav.Item className="d-flex align-items-center">
<Nav.Link className="lrgNavItem pl-4 pr-0" href="#contact">
Contact
</Nav.Link>
{/* this is where I'd like to render a <Coin/> element based on if the previous sibling <Nav.Link className="is-active"> is true */}
</Nav.Item>
</Nav>
</ScrollspyNav>
</Col>
</Row>
);
}
}
export default LrgNav;发布于 2019-09-09 16:39:14
您可以将Nav.Item抽象为一个函数来为您处理它:
const NavItemAndCoin = () => {
const isActive = someDeterminationForActivity();
const classes = `about-me lrgNavItem pl-4 pr-0 ${isActive ? 'is-active'}`;
return (
<Nav.Item className="d-flex align-items-center">
<Nav.Link
className={classes}
href="#about-me"
>
About Me
</Nav.Link>
{isActive && <Coin ... />}
</Nav.Item>
);
}然后,您可以使用NavItemAndCoin来代替NavItem
<NavItemAndCoin />您仍然需要找出一些方法来获得位置(即,someDeterminationForActivity()方法)。
https://stackoverflow.com/questions/57850304
复制相似问题