美文网首页
③React-router的常用操作

③React-router的常用操作

作者: loycoder | 来源:发表于2017-12-12 19:05 被阅读8次

以下代码,React-router 是 2.x 版,本文的内容只适合这个版本,与最新的 4.x 版不兼容。目前,官方同时维护 2.x 和 4.x 两个版本,所以前者依然可以用在项目中。

效果图:


image.png
import React from 'react';
import ReactDOM from 'react-dom';
import  {Router,Route,hashHistory,browserHistory,Link,IndexRoute,Redirect,IndexLink } from 'react-router';

require('./style.css');

/**
 *  本节知识点:
 *   路由的通配符匹配:
 *      1.路由匹配规则是从上到下执行,一旦发现匹配,就不再其余的规则了。
 *      2.()是可选匹配
 *      3.*是任意字符匹配
 *      4.**贪婪模式,在不确定参数个数的情况下匹配
 *
 *      5.记住一个原则: 像这种通配符的匹配,写在最底部,防止出现以下情况:
 *       <Router>
 <Route path="/:userName/:id" component={UserPage}/>
 <Route path="/about/me" component={About}/>
 </Router>

 上面代码中,用户访问/about/me时,不会触发第二个路由规则,
 因为它会匹配/:userName/:id这个规则。因此,带参数的路径一般要写在路由规则的底部。

 其他知识点:
 1.关于Link  组件的 activeClassName 属性与 activeStyle
 是指定 如果是访问了当前的  路由,就指定 class样式, activeStyle 是内联样式

 2.关于IndexRoute 组件。 当用户访问 / 的时候显示, 注意:
 IndexRoute 没有 path 属性

 3.在Router组件之外,导航到路由页面,可以使用浏览器的History API,像下面这样写。
 browserHistory.push('/some/path');

 4.关于 IndexLink 和 onlyActiveOnIndex 属性
 IndexLink其实就是   onlyActiveOnIndex 的包装而已, 2者的效果是一样的

 因为/会匹配任何子路由。而IndexLink组件会使用路径的精确匹配。
 如果链接到根路由/,不要使用Link组件,而要使用IndexLink组件。
 这是因为对于根路由来说,activeStyle和activeClassName会失效,或者说总是生效,

 5.关于 history属性,一共有3个属性,分别是:

 1.browserHistory
 如果设为browserHistory,浏览器的路由就不再通过Hash完成了,而显示正常的路径example.com/some/path,
 背后调用的是浏览器的History API。

 2.hashHistory
 如果设为hashHistory,路由将通过URL的hash部分(#)切换,URL的形式类似example.com/#/some/path。

 3.createMemoryHistory
 createMemoryHistory主要用于服务器渲染。它创建一个内存中的history对象,不与浏览器URL互动.
 const history = createMemoryHistory(location)
 */


//browserHistory.push('/List');

/**
 * 可选参数的匹配x
 */
class About extends React.Component {
    render() {
        return <div>
            这个路由匹配是: 可选匹配 <br />
            接受参数name:{this.props.params.name}
        </div>;
    }
}

/**
 * 指定参数个数时的匹配
 * @returns {XML}
 * @constructor
 */
const List = ()=> {
    return <div>
        <ul>
            <li><Link to="/List/test01/react">react</Link></li>
            <li><Link to="/List/test02/vue">vue</Link></li>
        </ul>
    </div>;
}

class ListChild extends React.Component {
    render() {
        return <div>{this.props.params.myArgs}</div>;
    }
}

/**
 * 匹配 *.*的路由
 */
class File extends React.Component {

    render() {
        //如果是 这种*号匹配,取值应该这样取:
        var args = this.props.params.splat;
        return <div>{args.join(".")}</div>;
    }
}


class Greed extends React.Component {

    render() {
        //如果是 这种** 贪婪批量,取值应该这样取:
        var args = this.props.params.splat;
        return <div>{args.join(".")}</div>;
    }
}
/**
 * 默认访问
 */
class Home extends React.Component {
    render() {
        return <div>直接通过域名访问显示的页面..</div>;
    }
}

/**
 * 路由钩子案例
 */
class MemberCenter extends React.Component {
    render() {
        return <div>您已进入会员中心..</div>;
    }
}

class APP extends React.Component {

    handleSubmit(event) {
        event.preventDefault();
        //console.log(event.target.elements);

        const name = this.refs.name.value;
        const job = this.refs.job.value;

        const path = `/greed/${name}/${job}.jpg`;
        browserHistory.push(path);

        // this.context.router.push(path)
    }

    render() {
        return (
            <div>
                React Router 常用操作:
                <ul>
                    <li><IndexLink to="/" activeClassName="active" component={Home}>通过IndexLink返回首页</IndexLink></li>
                    <li><Link onlyActiveOnIndex activeClassName="active" to="/">通过onlyActiveOnIndex返回首页</Link></li>
                </ul>

                <ul>
                    <li><Link activeClassName="active" to="About">About不带参数访问</Link></li>
                    <li><Link activeClassName="active" to="/About/loycoder">About携带参数</Link></li>
                </ul>

                <ul>
                    <li><Link activeClassName="active" to="/List">list 多层路由规则指向</Link></li>
                </ul>

                <ul>
                    <li><Link activeClassName="active" to="/renyi/index.php">指定后缀的,任意字符匹配-模式1</Link></li>
                    <li><Link activeClassName="active" to="/renyi/index.html">指定后缀的,任意字符匹配-模式2</Link></li>
                </ul>

                <ul>
                    <li><Link activeClassName="active" to="/greed/参数1/参数2/参数N/1.jpg">贪婪模式匹配,【在不确定参数个数的情况下使用】</Link></li>
                </ul>

                <ul>
                    <li><Link activeClassName="active" to="/redirect">路由跳转</Link></li>
                </ul>

                <hr />
                <ul>
                    <li>路由钩子的使用</li>
                    <li><Link to="/Auth">点击进入会员中心。【当前假设未登录】</Link></li>
                </ul>

                {this.props.children}

                <hr />
                <p>表单处理,提交参数</p>
                <form onSubmit={this.handleSubmit.bind(this)}>
                    <ul>
                        <li>姓名:<input ref="name" type="text"/></li>
                        <li>职业:<input ref="job" type="text"/></li>
                        <li><input type="submit" value="submit"/></li>
                    </ul>
                </form>
            </div>
        );
    }
}

/**
 * 进入路由的验证
 */
const onEnter = (nextState, replace) => {
    if (1 == 2) {  //假设未登录
        alert('您没有登录,将跳转到首页');
        replace({pathname: '/'})
    }
}
const  onLeave=(nextState, replace) => {
    alert('即将要离开');
    return false;
}

ReactDOM.render(
    <Router history={browserHistory}>
        <Route path="/" component={APP}>
            <IndexRoute component={Home}/>

            <Redirect from="/redirect" to="/About/我是跳转携带的参数"/>

            <Route path="/List" component={List}></Route>

            <Route path="/List/:myName/:myArgs" component={ListChild}></Route>

            <Route path="About(/:name)" component={About}/>

            <Route path="renyi/*.*" component={File}/>

            <Route path="/greed/**/*.jpg" component={Greed}/>

            {/*当用户进入路由,和离开路由的验证*/}
            <Route path="/Auth" onEnter={onEnter} onLeave={onLeave}  component={MemberCenter}></Route>
        </Route>
    </Router>,
    document.getElementById('app')
);

相关文章

网友评论

      本文标题:③React-router的常用操作

      本文链接:https://www.haomeiwen.com/subject/uegnixtx.html