title: React教程
date: 2023-04-06 20:51:55
tags: [react]
categories: [js]


React路由的基本使用

zxl@linux:~/Desktop$ node -v
v16.17.0
zxl@linux:~/Desktop$ npm -v
8.15.0

npm i -g create-react-app 

create-react-app router-demo1

cd router-demo1

npm start

# 安装路由
npm i react-router-dom

index.js

import React from "react";
import ReactDOM from "react-dom";
import {BrowserRouter} from "react-router-dom"
import App from "./App";

ReactDOM.render(
    <BrowserRouter>
        <App/>
    </BrowserRouter>,
    document.getElementById("root")
)

App.jsx

import React from 'react'
import {Link,Route} from 'react-router-dom'
import Home from './components/Home'
import About from './components/About'

export default function App() {
  return (
    <div>
        <div className="row">
            <div className="col-xs-offset-2 col-xs-8">
                <div className="page-header"><h2>React Router Demo</h2></div>
            </div>
        </div>
        <div className="row">
            <div className="col-xs-2 col-xs-offset-2">
                <div className="list-group">

                    {/* 原生html中,靠<a>跳转不同的页面 */}
                    {/* <a className="list-group-item" href="./about.html">About</a>
                    <a className="list-group-item active" href="./home.html">Home</a> */}

                    {/* 在React中靠路由链接实现切换组件--编写路由链接 */}
                    <Link className="list-group-item" to="/about">About</Link>
                    <Link className="list-group-item" to="/home">Home</Link>
                </div>
            </div>
            <div className="col-xs-6">
                <div className="panel">
                    <div className="panel-body">
                        {/* 注册路由 */}
                        <Route path="/about" component={About}/>
                        <Route path="/home" component={Home}/>
                    </div>
                </div>
            </div>
        </div>
    </div>
  )
}

About/index.jsx

import React from 'react'

export default function About() {
  return (
    <div>About</div>
  )
}

Home/index.jsx

import React from 'react'

export default function Home() {
  return (
    <div>Home</div>
  )
}

index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>react脚手架</title>
		<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
		<link rel="stylesheet" href="/css/bootstrap.css">
		<style>
			.atguigu{
				background-color: rgb(209, 137, 4) !important;
				color: white !important;
			}
		</style>
	</head>
	<body>
		<div id="root"></div>
	</body>
</html>