React JS:点击NavLink隐藏父组件文本的实现方法
Got it, let's work through this! The key here is using state lifting—we'll manage the visibility of the intro text in the parent Portfolio component, then pass a function to the child PortfolioMenu to update that state when a NavLink is clicked. Here's how to implement it step by step:
Step 1: Update the Parent Portfolio Component
First, we'll add a state variable to track whether the intro text should be visible, plus a handler function to hide it. We'll pass this handler to the child component as a prop.
import React, { useState } from 'react' import PortfolioMenu from './PortfolioMenu' const Portfolio = () => { // State to control visibility of the intro text const [showIntro, setShowIntro] = useState(true) // Handler function to hide the intro text const handleHideIntro = () => { setShowIntro(false) } return ( <div className="wrapper2"> {/* Conditionally render the <p> tag based on showIntro state */} {showIntro && <p> Here is an Introduction text </p>} {/* Pass the handler to the child component */} <PortfolioMenu onHideIntro={handleHideIntro} /> </div> ) } export default Portfolio
Step 2: Modify the Child PortfolioMenu Component
Next, we'll attach the parent's handler function to the onClick event of each NavLink in the child. When a link is clicked, it will trigger the handler to update the parent's state and hide the intro text.
Assuming your PortfolioMenu uses react-router-dom's NavLink, here's the modified code:
import React from 'react' import { NavLink } from 'react-router-dom' const PortfolioMenu = ({ onHideIntro }) => { return ( <nav> {/* Add onClick event to each NavLink to trigger the parent's handler */} <NavLink to="/portfolio/project1" onClick={onHideIntro} className={({ isActive }) => isActive ? "active-link" : ""} > Project 1 </NavLink> <NavLink to="/portfolio/project2" onClick={onHideIntro} className={({ isActive }) => isActive ? "active-link" : ""} > Project 2 </NavLink> {/* Add more NavLinks as needed */} </nav> ) } export default PortfolioMenu
How This Works
- The parent component owns the
showIntrostate, which determines if the<p>tag is rendered (using the&&conditional render pattern). - The
handleHideIntrofunction updates this state tofalse, which hides the intro text. - We pass this function to the child as a prop (
onHideIntro). - When any NavLink in the child is clicked, it calls
onHideIntro, which triggers the state update in the parent and hides the text.
If you ever need to show the intro text again later, you could extend this setup with an additional state update function to toggle visibility back on!
内容的提问来源于stack exchange,提问作者claudiopb

