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
相关产品推荐
相关产品推荐

