Javascript

React的路由跳转

本文主要是介绍React的路由跳转,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

要实现React的路由跳转,需要用react-router-dom组件。

"react-router-dom": "^6.2.1"

在App.js配置路由

import React, { Component } from 'react';
import './App.scss';  // 引入样式文件
import { HashRouter, Route, Routes, Navigate } from "react-router-dom";
import Home from './view/Home.jsx';
import Config from './view/Config.jsx';
import Draw from './view/Draw.jsx';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
      <HashRouter>
        <main>
            <Routes>
              <Route path="/home" exact element={<Home />}/>
              <Route path="/config" exact element={<Config />}/>
              <Route path="/draw" exact element={<Draw />}/>
              <Route path="*" element={<Navigate to="/home" />} />
            </Routes>
        </main>
      </HashRouter>
    );
  }
}
export default App;

新建Home.jsx,进行路由跳转

import React, { Component } from 'react';
import { Button } from 'antd'
import { Link } from "react-router-dom";

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  jumpToConfigPage(){

  }

  render() {
    return (
      <div>
        <h1>红包幸运抽奖系统</h1>
        <center className="btns">
          <Link to="/config">
            <Button type="primary" shape="round">配置</Button>
          </Link>
          <Link to="/draw">
            <Button type="primary" shape="round">抽奖</Button>
          </Link>
        </center>
      </div>
    );
  }
}
export default Home;

新建Draw.jsx

import React, { Component } from 'react';

class Draw extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
      <div>
        <h1>Draw</h1>
      </div>
    );
  }
}
export default Draw;

新建Config.jsx

import React, { Component } from 'react';

class Config extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
      <div>
        <h1>Config</h1>
      </div>
    );
  }
}
export default Config;

即可。

这篇关于React的路由跳转的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!