为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
React.JS

官网文档
https://reacttraining.com/react-router/core/guides/philosophy



页面路由

Hash 路由


H5路由

只对后退记录有效



// 页面路由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);
}

// 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 路由



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




将参数传给组件



作者:紫霞等了至尊宝五百年
链接:https://www.jianshu.com/p/dcb539acea23
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 1
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消