Giter VIP home page Giter VIP logo

Comments (1)

guowei55555 avatar guowei55555 commented on August 27, 2024

路由的使用步骤

import React from 'react';
import ReactDOM from 'react-dom';
// 1.先安装react-router-dom
// 2.导入BrowserRouter as Router,Route,Link
import {BrowserRouter as Router,Route,Link} from 'react-router-dom'
// 路由的基本使用
const First=()=><div>1233</div>
const App=()=>{
    return (
        // 3.使用Router包裹组件元素
        <Router>
        <div>
            <h1>路由基础</h1>
            {/* 4.使用Link设置路径入口 会被编译为a标签 */}
            <Link to="/first">页面7</Link>
            {/* 5.使用Route中path表示路径跳转,component  表示要展示的组件 Route写在哪,展示的内容就渲染在哪 */}
            <Route path="/first" component={First}></Route>
        </div>
        </Router>
    )
}
ReactDOM.render(<App />, document.getElementById('root'));

路由执行过程

1.点击link组件(a标签),修改了浏览器地址栏中的url
2.React路由监听到地址栏中url的变化
3.React 路由内部遍历所有Router组件,使用路由规则(path)与pathname进行匹配
4.当路由规则(path)能够匹配地址栏中的pathname时,就展示该Route组件的内容

编程式导航:

通过JS代码来实现页面跳转
history是React路由提供的,用于获取浏览器历史记录的相关信息
push(path):跳转到某个页面,参数path表示要跳转的地址
go(n):前进或后退到某个页面,参数n表示前进或后退页面数量

class Login extends Component {
handleLogin = () => {
// 使用编程式导航实现页面之间的跳转
this.props.history.push('/home')
}
render() {...省略其他代码} }
在函数组件中使用
props.history.push("/home")
---"/home"  表示将要跳转的页面路径


from blogs.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.