使用react-router-dom做移动端路由 2019-0

2019-08-12  本文已影响0人  讨厌西红柿

今天天气很好,赶到公司也是热的汗流浃背...

react-router 与 react-router-dom的关系

react-router-domreact-router为主分支关系,react-router v4之后,分为了几个独立的包

react-router-dom依赖于react-router,大多组件都只是从react-router中引入然后直接导出,不同的就是多了 <Link> <BrowserRouter>组件。所以web应用只需要引入react-router或者react-router-dom一项即可。

主要组件

1. Router

2. Switch

保证只渲染第一个匹配location的组件,上代码

<Route path="/about" component={About}/>
<Route path="/:user" component={User}/>
<Route component={NoMatch}/>

上述Route节点,如果访问/about路径,则About,User,NoMatch三个组件都将被渲染,因为三个path都被匹配成功,可能这并不是你想要的结果。如果包裹Switch组件,则只会渲染第一个匹配的组件About

<Switch>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
</Switch>

3. Route

负责location匹配及组件渲染的组件,通常作为Switch或者Router子组件。参数包括exact ,path, component, render, children,三个渲染方法中(component, render, children)只能选择一个,大多数情况都只是使用component就够了。

4. Link

一个文本导航组件,跟<a>标签有点类似,不过是路由跳转。

<Link to="/about">About</Link>

点击About就会直接跳到/about路径。

< NavLink >一个特殊版本<Link>,它将在与当前URL匹配时为渲染元素添加样式属性。

直接传入className

<NavLink to="/faq" activeClassName="selected">
  FAQs
</NavLink>

或者直接传入style样式

<NavLink
  to="/faq"
  activeStyle={{fontWeight: "bold",color: "red" }}
>
  FAQs
</NavLink>

5. Redirect

路由重定向组件

<Redirect exact from="/" to="/dashboard" />

from为匹配的路径,如果匹配成功,不会加载组件,而是重定向到to指定的路径。exact表示路径需要完全匹配。

实例

1、创建一个路由配置routerConfig,用来集中管理多个路由组件及属性。

const routerConfig = [
  {
    path: '/',
    exact:true,
    component: Startup
  },
  {
    path: '/main',
    component: App
  },
  {
    path: '/welcome',
    component: Welcome
  }
];

2、自定义一个AppRouter组件,解析routerConfig,创建Route等组件

import React, { Component } from 'react';
import { Switch, Route, MemoryRouter } from 'react-router-dom';
import routerConfig from '../../routerConfig';

class AppRouter extends Component {
  /**
   * 渲染路由组件
   */
  renderNormalRoute = (item, index) => {
    return item.component ? (
      <Route
        key={index}
        path={item.path}
        component={item.component}
        exact={item.exact}
      />
    ) : null;
  };

  render() {
    return (
      <MemoryRouter>
      <Switch>
        {/* 渲染路由表 */}
        {routerConfig.map(this.renderNormalRoute)}

        {/* 首页默认重定向到 /dashboard */}
        {/*<Redirect exact from="/" to="/dashboard" />*/}

      </Switch>
      </MemoryRouter>
    );
  }
}

export default AppRouter;

因为目前是移动端app路由,所以使用的是MemoryRouter,基本也用不上Redirect。这里也可以再封装一层,写一些固定布局,不随路由变化的布局。

3、最后再render AppRouter组件

ReactDOM.render(
    <AppRouter />,
  ICE_CONTAINER
);

4、在页面中使用

import {withRouter} from 'react-router-dom';

@withRouter
class Startup extends Component {
    // .....
}

使用withRouter注入相关类中,直接调用类属性中的history.push方法就可直接跳转路由

this.props.history.push("/main");

允许带入参数

this.props.history.push("/main", {type:1});

或者直接写入路径中

this.props.history.push("/main?type=1");

至此,就简单的集成了react-router-dom

关于react-router,其实还有很多很多没有写,但是呢,日记就先写到这里,想太多一天也写不完,就只是简单记录下个人理解及代码过程。end...

上一篇 下一篇

猜你喜欢

热点阅读