继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

React.js实战之Router原理及 React-router

BIG阳
关注TA
已关注
手记 429
粉丝 70
获赞 457

https://reacttraining.com/react-router/core/guides/philosophy

webp


webp


页面路由

webp

Hash 路由

webp


webp

H5路由

只对后退记录有效


webp


webp

// 页面路由window.location.href = 'http://www.baidu.com';
history.back();// hash 路由window.location = '#hash';window.onhashchange = function(){    console.log('current hash:', window.location.hash);
}// h5 路由// 推进一个状态history.pushState('name', 'title', '/path');// 替换一个状态history.replaceState('name', 'title', '/path');// popstatewindow.onpopstate = function(){    console.log(window.location.href);    console.log(window.location.pathname);    console.log(window.location.hash);    console.log(window.location.search);
}

webp

// react-router
import React from 'react';
import ReactDOM from 'react-dom';
import { HashRouter as Router, Switch, Route, Link } from 'react-router-dom'


class A extends React.Component{
    constructor(props){
        super(props)
    }
    render(){
        return (            <div>
                Component A                <Switch>
                    <Route exact path={`${this.props.match.path}`} render={(route) => {
                        return <div>当前组件是不带参数的A</div>
                    }}/>                    <Route path={`${this.props.match.path}/sub`} render={(route) => {
                        return <div>当前组件是Sub</div>
                    }}/>                    <Route path={`${this.props.match.path}/:id`} render={(route) => {
                        return <div>当前组件是带参数的A, 参数是:{route.match.params.id}</div>
                    }}/>                </Switch>
            </div>
        )
    }
}

class B extends React.Component{
    constructor(props){
        super(props)
    }
    render(){
        return <div>Component B</div>
    }
}

class Wrapper extends React.Component{
    constructor(props){
        super(props)
    }
    render(){
        return (            <div>
                <Link to="/a">组件A</Link>
                <br/>
                <Link to="/a/123">带参数的组件A</Link>
                <br/>
                <Link to="/b">组件B</Link>
                <br/>
                <Link to="/a/sub">/a/sub</Link>
                {this.props.children}            </div>
        );
    }
}

ReactDOM.render(    <Router>
        <Wrapper>
            <Route path="/a" component={A}/>
            <Route path="/b" component={B}/>
        </Wrapper>
    </Router>,
    document.getElementById('app')
);

通过以上代码,首先演示 Hash 路由


webp


再演示 H5路由,即修改此处


webp


webp


将参数传给组件

webp




作者:一生只为虞美人
链接:https://www.jianshu.com/p/dcb539acea23


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP