Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react中的路由的使用 #52

Open
zyb970821 opened this issue Jun 22, 2021 · 1 comment
Open

react中的路由的使用 #52

zyb970821 opened this issue Jun 22, 2021 · 1 comment

Comments

@zyb970821
Copy link

No description provided.

@guowei55555
Copy link

guowei55555 commented Jun 24, 2021

路由的使用步骤

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"  表示将要跳转的页面路径


@Dogtiti Dogtiti removed the Cbayel label May 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants