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

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有以下变动:

  1. 原Switch组件替换为Routes组件
  2. Route的component属性替换为element属性,值为组件实例:<Route path="/wallet-connect" element={<WalletConnect />} />
  3. 类组件跳转需要自行封装高阶组件获取navigate方法,或直接改为函数组件使用useNavigate钩子实现跳转。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:54:04