Browse Source

react-router

e 9 months ago
parent
commit
890dbc1d6c

+ 4 - 1
react/react高阶/React路由.md

@@ -21,4 +21,7 @@ export default router
 在根节点中抛出路由:抛出格式:<RouterProvider router={router} />
 ### 2.嵌套路由
 ### 3.动态路由
-### 4.查询参数
+### 4.查询参数
+### 5.导航
+#### 5.1 声明式导航
+#### 5.2 编程式导航

+ 10 - 1
react/react高阶/project1/src/components/Header.css

@@ -12,5 +12,14 @@
     background-color: black;
 }
 .header li a{
-    color: #087EA4;
+    color: #fff;
+}
+.active {
+    color: red !important;
+}
+.pending {
+    color: #ff0 !important;
+}
+.normal {
+    color: #087EA4 !important;
 }

+ 7 - 4
react/react高阶/project1/src/components/Header.jsx

@@ -1,17 +1,20 @@
-import {Link} from 'react-router-dom';
+import {Link,NavLink} from 'react-router-dom';
 import './Header.css';
 function Header() {
+    const handleActive = ({ isActive, isPending }) =>
+    isPending ? "pending" : isActive ? "active" : "normal"
     return (
         <>
+        {/* 声明式导航:Link NavLink */}
             <ul className='header'>
                 <li>
-                    <Link to={{pathname:'/'}}>首页</Link>
+                    <NavLink className={handleActive} to={{pathname:'/'}}>首页</NavLink>
                 </li>
                 <li>
-                    <Link to={{pathname:"/about"}}>相关</Link>
+                    <NavLink className={handleActive} to="/about">相关</NavLink>
                 </li>
                 <li>
-                    <Link to={{pathname:"/product"}}>商品</Link>
+                    <NavLink className={handleActive} to={{pathname:"/product"}}>商品</NavLink>
                 </li>
             </ul>
         </>

+ 11 - 0
react/react高阶/project1/src/pages/Detail.css

@@ -0,0 +1,11 @@
+.btn {
+    position: fixed;
+    bottom: 0;
+    left: 0;
+    width: 100%;
+    height: 60px;
+    text-align: center;
+    line-height: 60px;
+    background-color: #000;
+    color: #087EA4;
+}

+ 8 - 1
react/react高阶/project1/src/pages/Detail.jsx

@@ -1,12 +1,19 @@
-import {useParams,useSearchParams,useLocation} from 'react-router-dom';
+import {useParams,useSearchParams,useLocation,useNavigate} from 'react-router-dom';
+import './Detail.css'
 function Detail() {
     let {productId} = useParams();
     let [searchParams] = useSearchParams();
     let {state} = useLocation();
+    let go = useNavigate();
+    function handleBack() {
+        // 编程式导航
+        go(-1);
+    }
     return (
         <>
             <h1>详情</h1>
             <p>当前浏览商品的ID是:{productId || searchParams.get('productId') || state.productId}</p>
+            <button className='btn' onClick={handleBack}>返回上级</button>
         </>
     )
 }