React從入門到放棄(5):ReactRouter4

快速入門

安裝:npm i -S react-router react-router-domreact

GitHub:ReactTraining/react-routerwebpack

React Router中有三種類型的組件:路由器組件(BrowserRouter),路由匹配組件(Route)和導航組件(Link)。git

路由器

每一個React Router應用程序的核心應該是一個路由器組件。github

對於Web項目,react-router-dom提供BrowserRouterHashRouter路由器。web

路由器會包含全部路由組件。須要注意路由器節點下只能一個根節點。npm

路由匹配組件

Route:bash

path路徑(string): 路由匹配路徑。(沒有path屬性的Route 老是會 匹配);
exact精準(bool):爲true時,則要求路徑與location.pathname必須徹底匹配;
strict嚴格(bool):爲true時,有結尾斜線的路徑只能匹配有斜線的location.pathname;babel

strict示例:react-router

路徑 location.pathname strict 是否匹配
/one/ /one true
/one/ /one/ true
/one/ /one/two true

路由示例:app

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

import App from './App.js';


function NavBar(){
    return (
        <Router>
            <div>
                <Route component={Nav} />
                <Switch>
                    <Route exact path='/' component={() => (<div>hello</div>)} />
                    <Route path='/app' component={App} />
                </Switch>
            </div>
        </Router>
    );
}

導航組件

Link:在應用中,提供導航功能

NavLink:Link的一個特殊版本,當匹配指定URL的時候,會給元素添加style

示例:

<Link to="/profile"/>
<NavLink to="/profile" activeStyle={{color:'red'}}/>

Code Split

使用Router的Code Split(按需加載)依賴webpack(默認支持)、babel-plugin-syntax-dynamic-import和react-loadable。

babel-plugin-syntax-dynamic-import: 意味着Babel處理時不會作任何額外的轉換。該插件只是容許Babel解析動態導入

npm i babel-plugin-syntax-dynamic-import react-loadable -S

.bashrc:

{
  "presets": [
    "react"
  ],
  "plugins": [
    "syntax-dynamic-import"
  ]
}

代碼示例:

import Loadable from 'react-loadable';

function Loading(){
  return (
    <div> Loading... </div>
  )
}

const Clock = Loadable({
  loader: () => import('./Clock'),
  loading: Loading,
});

export default class LoadableClock extends React.Component {
  render() {
    return <Clock />;
  }
}
相關文章
相關標籤/搜索