You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router点击跳转后如何让ContentPage在独立新页面渲染

以上为TutorialCard.jsx组件生成的链接卡片

问题根因

你当前的路由配置没有对卡片列表做路由规则限制,卡片列表直接写在Router下和Switch平级,所以不管路由匹配到什么路径,卡片列表都会一直渲染,就会出现和ContentPage并排的情况。


方案1:同站路由跳转,点击后替换卡片列表,当前页独立区块展示ContentPage

修改MainComponent.jsx路由结构

//other code
<Router>
  <Switch>
    {/* 首页路由:只有路径为/时渲染卡片列表 */}
    <Route exact path="/">
      <CardGroup>
        {cards.map((value,idx) => { return <TutorialCard key={idx} val={value} /> })}
      </CardGroup>
    </Route>
    {/* 内容页路由:匹配到/subject/:title时只渲染内容页 */}
    <Route path="/subject/:title" component={ContentPage}/>
  </Switch>
</Router>
//other code

修正ContentPage拼写错误

原代码组件名少写了字母n,会导致组件渲染失败:

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

方案2:点击卡片直接打开新浏览器标签页展示内容页

如果需要完全独立的新页面渲染,不需要调整路由结构,只需要修改TutorialCard.jsx的Link组件,加新标签页打开属性即可:

//该组件用于生成跳转链接
export default function TutorialCard({ val }) {
  return (
    <Card border="primary" style={{ width: '18rem' }} className='cards'>
      {/* target="_blank"指定新标签页打开,rel属性是安全配置 */}
      <Link exact to={`/subject/${val}`} target="_blank" rel="noopener noreferrer">
        <Card.Header className="text-center">
          <h6>{val}</h6>   
        </Card.Header>
        <Card.Body>
          <img src={cardSvg} className="fitImage" alt="卡片封面"/>
        </Card.Body>
      </Link>
    </Card>
  );
}

内容的提问来源于stack exchange,提问作者Rashedul Islam Emon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 17:24:01