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

Next.js中点击按钮如何在新标签页打开外部链接?

在Next.js中实现按钮点击打开外部链接(新标签页)

针对你提供的按钮代码,有两种简洁的方法实现点击后在新标签页打开Google:

方法一:给按钮添加onClick事件处理函数

直接给按钮绑定点击事件,通过window.open打开外部链接:

import styles from './你的组件样式文件.module.css';

const GoogleButton = () => {
  const handleOpenGoogle = () => {
    // 第三个参数为安全配置,必须添加
    window.open('https://www.google.com', '_blank', 'noopener,noreferrer');
  };

  return (
    <button 
      type="button" 
      className={styles.googleButton}
      onClick={handleOpenGoogle}
    >
      <img className={styles.image} src="/assets/pictures/google.jpg" alt="Google图标" />
      <p className={styles.buttonText}>Go To Google</p>
      <img src="/assets/icons/external-link.svg" alt="外部链接图标" />
    </button>
  );
};

export default GoogleButton;

关键说明:

  • _blank参数指定在新标签页打开链接
  • noopener,noreferrer是浏览器安全要求,防止新页面获取原页面控制权,避免安全风险
  • 图片路径使用/开头,对应Next.js项目public目录下的资源(需确保assets文件夹放在public内)

方法二:用原生a标签包裹按钮

Next.js中外部链接无需使用next/Link组件,直接用原生<a>标签包裹按钮即可:

import styles from './你的组件样式文件.module.css';

const GoogleButton = () => {
  return (
    <a 
      href="https://www.google.com" 
      target="_blank" 
      rel="noopener noreferrer"
      style={{ display: 'inline-block' }} // 避免a标签破坏按钮布局
    >
      <button type="button" className={styles.googleButton}>
        <img className={styles.image} src="/assets/pictures/google.jpg" alt="Google图标" />
        <p className={styles.buttonText}>Go To Google</p>
        <img src="/assets/icons/external-link.svg" alt="外部链接图标" />
      </button>
    </a>
  );
};

export default GoogleButton;

关键说明:

  • rel="noopener noreferrer"必须添加,符合现代浏览器安全规范
  • 给a标签设置display: inline-block或对应样式类,保证按钮布局正常
  • 该方法更符合HTML语义化,同时保留按钮原有交互样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:35:15