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

如何实现点击React Button组件时在新标签页打开链接?

实现自定义Button组件链接在新标签页打开

要让你的Button组件点击后在新标签页打开链接,只需给组件内部的<a>标签添加target="_blank"属性,同时为了安全加上rel="noopener noreferrer",具体操作分两步:

1. 修改Button组件,支持新标签页属性

更新Button组件代码,接收target和rel属性(可设置默认值让所有按钮默认新标签页打开,也可留空让父组件按需传入):

import styles from "./button.module.scss";

const Button = ({ content, icon, type, href, target="_blank", rel="noopener noreferrer" }) => {
  return (
    <>
      <a
        className={`${styles.button} ${
          type === "primary" ? styles.primaryButton : styles.secondaryButton
        }`}
        href={href}
        target={target}
        rel={rel}
      >
        <i className={`fas fa-${ icon }`}></i>
        {content}
      </a>
    </>
  );
};

export default Button;

2. 按需控制单个Button的打开方式

如果某个按钮不需要在新标签页打开(比如mailto链接),可以在调用时覆盖默认属性:

<Button
  href="mailto:nisaefendioglu0@gmail.com"
  type="secondary"
  content="Contact"
  icon="paper-plane"
  target="_self"
/>

关于rel="noopener noreferrer"的说明

这是前端安全最佳实践:它能阻止新打开的页面通过window.opener访问原页面的DOM和JavaScript上下文,避免潜在的钓鱼或恶意脚本攻击。

内容的提问来源于stack exchange,提问作者Nisa Efendioglu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:27:49