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

NextJS环境下React类组件点击按钮重定向外部页面问题咨询

错误原因

useRouter 是 Next.js 提供的 React Hook,仅支持在函数组件/自定义 Hook 中调用,类组件中直接使用会触发 Hook 调用规则报错。另外你要跳转的是外部站点,不需要使用任何路由工具,直接用浏览器原生 API 即可实现。

正确实现代码

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          {/* 点击后当前页面跳转到谷歌首页 */}
          <button onClick={() => window.location.href = 'https://www.google.com/'}> Join </button>
          {/* 如需新标签页打开,替换为下面的代码即可
          <button onClick={() => window.open('https://www.google.com/', '_blank')}> Join </button>
          */}
        </div>
      </div>
    )
  }
}

export default App;

补充说明

如果你后续需要在 Next.js 类组件中实现内部路由跳转,可以使用 Next.js 提供的 withRouter 高阶组件包裹组件,从 props 中获取 router 实例使用,本次外部跳转场景无需使用该能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:21:00