Router

在React中使用react-router-dom路由css

使用react构建的单页面应用,要想实现页面间的跳转,首先想到的就是使用路由。在react中经常使用的有两个 包能够实现这个需求,是react-router和react-router-dom。此次主要对react-router-dom进行说明。前端

安装react

先进入项目目录。在项目命令行中执行:npm install react-router-dom npm

在组件中经过对象的解构方式获取到react-router-dom内置组件,在组件中,按需引入内置组件,在页面中使用:后端

路由的内置组件浏览器

1.1 HashRouter和BrowserRouter表示一个路由的根容器,将全部的路由相关的都包裹在HashRouter或BrowserRouter里面,在一个网站中,只须要使用一次根路由就能够了。react-router

1.2 区别: BrowserRouter--浏览器路由(属于后端路由)使用的是HTML5的新特性History,没有HashRouter(锚点定位)那样通用,低版本浏览器可能不支持。dom

               HashRouter--前端has路由(属于前端路由)在路径中包含#,至关于HTML的锚点定位网站

1.3Route 用来路由的,在Router上有两个比较重要的属性:path和component 注意事项:不该该在同一个router 上同时使用component和render渲染,component的优先级要高于render,若是同时使用render 会被忽略this

1.4 Link 表示一个路由的连接 有一个属性是---to

<Link to="/home" />

 NavLink

<NavLink activeClassName="" />

区别:一个点击的时候跳转,另外一个点击以后还会额外加一个类名,能够控制样式。

         若是更改class名的话就用activeClassName="xxx"

手动跳转页面

this.props.history.push("./home")

嵌套路由

JS实现路由跳转

jump(){
    window.location.href = "/news"  //js路由跳转的路径
}

render(){
    return (
        <BrowserRouter>
            <div>
                <h1>这是网站的根目录</h1>
                <hr />
                <button onClick={()=>{this.jump()}}>新闻</button>
                <hr />
                <Route path="/news" component={News}></Route>
            </div>
        </BrowserRouter>
    );
}

 

App.js

import React from 'react';
import './App.css';
import Home from './Home';

function App() {
  return (
    <Home />
  );
}

export default App;

Home.js

import React, { Component } from 'react'
import {Route,Link,Switch} from "react-router-dom"

export default class First extends Component {
  render() {
    return (
      <div>
            <p><Link className="link" to="/first">首页</Link></p>
            <p><Link className="link" to="/second">关于</Link></p>
            <p><Link className="link" to="/third">新闻</Link></p>
            <div style={{ padding: 24, background: '#fff', minHeight: 360 }}>
               <Switch>
                 <Route path="/first" component={First} />
                 <Route path="/second" component={Second} />
                 <Route path="/third" component={Third} />
               </Switch>
        </div>
      </div>
    )
  }
}        

路由传值

相关文章
相关标签/搜索