【问题标题】:Render a component in a specific section of page在页面的特定部分渲染组件
【发布时间】:2026-01-18 07:25:01
【问题描述】:

MainComponent.jsx

//other code
<CardGroup>
  <Router>
    {cards.map((value,idx) => { return <TutorialCard key={idx} val={value} /> })}
    <Switch>
      <Route path="/subject/:title" children={(props)=>{<ContentPage {...props}/>}}/>
    </Switch>
  </Router>
</CardGroup>
//other code

ContentPage.jsx

我想在特定部分/新页面中显示此组件。

export default function CotentPage(props){
  return <h1>This is content page-{props.match.params.title}</h1>  
}

TutorialCard.jsx

//this component create links.
export default function tutorialCard({ val }) {
  return (
    <Card border="primary" style={{ width: '18rem' }} className='cards'>
      <Link exact to={`/subject/${val}`}>
        <Card.Header className="text-center">
          <h6>{val}</h6>   
        </Card.Header>
        <Card.Body>
          <img src={cardSvg} className="fitImage"></img>
        </Card.Body>
      </Link>
    </Card>
  );
}

单击这些链接后,它会在链接之外呈现 ContentPage。但我想在新页面中呈现 ContentPage。我怎样才能做到这一点? 请帮忙!

【问题讨论】:

  • 这里有什么问题?
  • ContentPage 组件显示在链接之外。我想在特定部分/新页面中显示它。
  • 您的问题不清楚。你能补充一些信息吗?
  • @NITHINPB 我添加了更多信息。请检查一下。

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

原因是,卡片的渲染独立于您的路线。您需要在另一条路线中渲染您的卡片。像这样:

<Router>
  <Switch>
    <Route
      path="/"
      exact
      children={() => (cards.map((value, idx) => <TutorialCard key={idx} val={value} />))}
    />
    <Route
      path="/subject/:title"
      children={(props) => <ContentPage {...props} />}
    />
  </Switch>
</Router>

【讨论】:

  • 它不工作。使用这些代码时,链接不会呈现。
  • 您确定您在/ 路径中吗?