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

