react中的路由----常用组件说明

Router 组件

Router 组件:包裹整个应用,一个React 应用只需要使用一次

两种常用 Router:HashRouter和 BrowserRouter

HashRouter:使用 URL 的哈希值实现(localhost:3000/#/first)

(推荐)BrowserRouter:使用H5 的 history API 实现(localhost:3000/first)

import React from "react";
import ReactDOM from "react-dom";
// react路由
// 1、导入
import {
    
     HashRouter as Router, Route, Link } from "react-router-dom";
const First = () => <p>页面一的页面内容</p>;
const App = () => (
  // 2、包裹
  <Router>
    <div>
      <h1>React路由基础</h1>
      {
    
    /* 3、指定路由入口*/}
      <Link to="/first">页面1</Link>
      {
    
    /* 4、  路由规则(与入口对应)          匹配的组件     路由出口*/}
      <Route path="/first" component={
    
    First}></Route>
    </div>
  </Router>
);
ReactDOM.render(<App />, document.getElementById("root"));

在这里插入图片描述

Link 组件:用于指定导航链接(a 标签)

最终被渲染为a标签 to被渲染成href

		// to属性:浏览器地址栏中的pathname(location.pathname) 
		//改变浏览器地址里面的内容
		<Link to="/first">页面一</Link>

在这里插入图片描述

Route 组件:指定路由展示组件相关信息

path属性:路由规则
component属性:展示的组件
Route组件写在哪,渲染出来的组件就展示在哪

// path属性:路由规则 
// component属性:展示的组件
// Route组件写在哪,渲染出来的组件就展示在哪
<Route path="/first" component={First}></Route>

猜你喜欢

转载自blog.csdn.net/weixin_43131046/article/details/120293058