React点击按钮切换组件跳转至wallet-connect不生效问题求助
问题根源
- 点击事件回调的返回值不会被渲染到页面DOM中,你在
changeComp函数中返回的Router、Route结构完全不会生效,没有插入到页面渲染树里。 - 路由基础配置位置错误:
Router、Switch这类路由根容器和路由规则,需要提前配置在应用的顶层组件渲染逻辑中,不能在点击触发时才临时定义。 - 没有调用正确的路由跳转API:路由跳转不需要手动返回Route组件,应该调用路由库提供的专用跳转方法。
修复方案(基于react-router v5版本,你的代码中使用的Switch、component属性属于v5 API)
第一步:提前配置全局路由规则
在你的应用顶层组件(通常是App.js)中统一配置所有路由:
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import Home from './你当前按钮所在页面组件的路径'; import WalletConnect from './WalletConnect组件的路径'; class App extends React.Component { render() { return ( <Router> <Switch> {/* 原有页面的路由规则 */} <Route exact path="/" component={Home} /> {/* 提前声明钱包连接页的路由规则 */} <Route exact path="/wallet-connect" component={WalletConnect} /> </Switch> </Router> ) } } export default App;
第二步:修改按钮所在组件的跳转逻辑
用withRouter高阶组件包裹你的页面组件,获取路由跳转能力:
import { withRouter } from 'react-router-dom'; class 你的当前页面组件 extends React.Component { changeComp() { // 直接调用路由提供的跳转方法 this.props.history.push('/wallet-connect'); } render() { return ( {/* 注意:如果按钮不在form表单内,type改成button避免触发默认提交刷新 */} <button className="btn w-100 mt-3 mt-sm-4" onClick={() => this.changeComp()} type="button" > Sign In </button> ) } } // 导出时用withRouter包裹,组件才能拿到history等路由属性 export default withRouter(你的当前页面组件);
补充注意点
如果你使用的是react-router v6版本,API有以下变动:
- 原
Switch组件替换为Routes组件 Route的component属性替换为element属性,值为组件实例:<Route path="/wallet-connect" element={<WalletConnect />} />- 类组件跳转需要自行封装高阶组件获取
navigate方法,或直接改为函数组件使用useNavigate钩子实现跳转。
内容的提问来源于stack exchange,提问作者Zuffido
相关产品推荐
相关产品推荐

