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

React中按钮onclick跳转同页及卡片锚点新页跳转问题求助

问题解决方案

问题1:按钮添加onClick后点击跳转至当前页面

原因分析

若按钮被包裹在<form>标签内,HTML默认会将按钮视为submit类型,点击时触发表单提交,导致页面重载(跳转至当前页面)。即使没有表单,未正确阻止默认行为或按钮类型设置不当也会引发此问题。

解决方法

方法1:设置按钮类型为button

直接给Button组件添加type="button"属性,规避默认提交行为:

<Button 
  variant="" 
  className={classes["btn-cat"]}
  type="button"
  onClick={() => {
    // 这里编写按钮逻辑
  }}
>
  {showCat}
</Button>

方法2:在onClick中阻止默认行为

若无法修改按钮类型,在点击事件中调用event.preventDefault():

<Button 
  variant="" 
  className={classes["btn-cat"]}
  onClick={(e) => {
    e.preventDefault();
    // 这里编写按钮逻辑
  }}
>
  {showCat}
</Button>

问题2:点击卡片内锚点/图标在新标签页打开详情页

原因分析

你尝试的代码使用了错误的路径(src/comp/newsitem是文件路径而非路由地址),且window.location.href仅能在当前标签页跳转,无法实现新标签页打开需求。

解决方法

假设项目已配置路由,详情页路由为/newsitem/:id(:id为动态参数),以下两种方式均可实现需求:

方法1:使用window.open()打开新标签页

给FaLink图标添加点击事件,通过window.open()指定新标签页打开:

<FaLink 
  onClick={() => {
    // 拼接详情页路由,list.id为当前卡片的id
    const detailUrl = `/newsitem/${list.id}`;
    window.open(detailUrl, '_blank');
  }}
  style={{ cursor: 'pointer' }} // 添加鼠标指针样式提示可点击
/>

方法2:使用React Router的Link组件(推荐)

若项目使用React Router,直接用Link组件并设置target="_blank"和rel="noopener noreferrer"(符合安全规范):

import { Link } from 'react-router-dom';

// 在卡片内容中替换原有FaLink部分:
<Link 
  to={`/newsitem/${list.id}`}
  target="_blank"
  rel="noopener noreferrer"
  style={{ color: '#0aceff' }} // 保持原有颜色样式
>
  <FaLink />
</Link>

补充说明

确保路由配置中已定义详情页路由:

// 在路由配置文件中
import { Routes, Route } from 'react-router-dom';
import NewsItem from './src/comp/newsitem'; // 导入详情页组件

<Routes>
  {/* 其他路由 */}
  <Route path="/newsitem/:id" element={<NewsItem />} />
</Routes>

内容的提问来源于stack exchange,提问作者Farah Fahmy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:45:29