我想根据元素的先前同级是否具有某个className来有条件地呈现一个元素。
当用户位于页面上该Nav.Link上的href =“”位置时,Nav.Link会收到一个“ is-active”的className(这是通过第三方库实现的)。
我想根据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;
答案 0 :(得分:3)
您可以将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()方法)。