1

每当我单击 labCard.js 组件中的链接文本时,我想显示一个自定义组件 Resource.js。使用 Outlet 挂钩时,Resource 组件会显示在 lab Card 中,而 Body.js 组件不会被替换。Body.js 组件是 labCards 组件的集合。我希望每当我在 labCard 组件上单击 Begin 时显示资源组件来代替 body 组件。

这是 App 组件

import React from 'react'
import { Routes, Route } from 'react-router-dom'
import Navbar from './components/Navbar'
import Home from './components/Home'
import Body from './components/Body'
import AboutUs from './components/AboutUs'
import GetHelp from './components/GetHelp'
import Footer from './components/Footer'
import Resource from './subComponents/Resource'
import './App.css';

function App() {
  return (
    <div>
      <Navbar />
      <Routes>
        <Route path="/" element={ <Home /> } />
        <Route path="/body/*" element={ <Body /> } >
          <Route path="resource" element={ <Resource /> } />
        </Route>
        <Route path="/about" element={ <AboutUs /> } />
        <Route path="/help" element={ <GetHelp /> } />
      </Routes>
      <Footer />
    </div>
  );
}

export default App;

这是身体组件

import React from 'react'
import LabCard from '../subComponents/LabCard'
import { data } from '../data'
import './Body.css'

export default function Body() {
    const [labData, setLabData] = React.useState(data)
    let labCardElements = labData.map(lab => 
    <LabCard 
        key={lab.id} 
        labID={lab.id} 
        labType={lab.type}
        labTitle={lab.title} 
        labResourceUrl={lab.resourceUrl}
    />)
    return (
        <section className='experiment-body-section'>
            <h1 className='experiment-body--title'>Experiments</h1>
            <p className='experiment-body--description'>Here are all the experiments</p>
            <div className='experiment-body'>
                {labCardElements}
            </div>
        </section>
    )
}

这是 labCard 组件

import React from 'react'
import { Link } from 'react-router-dom'
import './Card.css'

export default function LabCard(props) {
    return (
        <div className='lab-card'>
            <p className='lab-card--id'>{props.labType}</p>
            <h2 className='lab-card--title'>{props.labTitle}</h2>
            <div className="parent">
                <div className='lab-card--overlay'></div>
                <Link to="resource" className='lab-card-overlay--button'>Begin</Link>
            </div>
        </div>
    )
}
4

1 回答 1

0

如果我正确理解您的问题/问题,那就是您不想同时渲染组件。BodyResource

Body在这种情况下,您应该在嵌套索引路由上进行渲染。默认情况下,两个嵌套路由都将呈Outlet现在父路由上。

<Route path="/body">
  <Route index element={<Body />} />               // <-- "/body"
  <Route path="resource" element={<Resource />} /> // <-- "/body/resource"
</Route>
于 2022-02-16T07:30:53.827 回答