1、页面参数获取,useParams()
useSearchParams
const [params1,setparams1] = useSearchParams()
包含两个数组对象
其一:路由对象,方法有get(),getAll()等等
其二:该变路由参数的函数
/*ocalhost:3000/user/detail/1?id=666&ada-1*/
const [params1, setparams1] = useSearchParams()
console.log(params1.get('id'));
//输出为‘666’
setparams1("id=666&id=123")
console.log(params1.getAll('id'));
//输出为['666', '123']
2、菜单匹配,高亮显示useLoaction、matchRoutes
以下只是一种解决思路
matchRoutes
参数1:所有的路由信息
参数2:loaction信息(location.pathname)
返回值:匹配数组,按照当前页面路由的嵌套层级依次返回匹配的路由信息数组
一般放到副作用Hook(useEffect)中进行操作
import { useOutlet, useLocation, Link,matchRoutes } from 'react-router-dom'
import router from '../../router';
export default function Layout() {
const location =useLocation();
const [path, setpath] = useState([]);
useEffect(() => {
const routes=matchRoutes(router, location.pathname);
console.log(9999988,routes);
const pathArr=[]
if(routes!==null){
for(let route of routes){
let path=route.route.path;
if(path){
pathArr.push(path)
}
}
}
setpath(pathArr)
}, [location.pathname]);
const result=useOutlet()
return (
<div style={{display:'flex'}}>
<div style={{flex:'0 0 200px'}}>
<div style={{ flex: '0 0 200px' }}>
<p style={path[1]=='/user'?{background:'aliceblue'}:null}> <Link to='/user'>用户</Link></p>
<p style={path[1]=='/user/detail/:id'?{background:'aliceblue'}:null}> <Link to='/user/detail/:id'>用户详情</Link></p>
<p style={path[1]=='/'?{background:'aliceblue'}:null}><Link to=''>首页</Link></p>
</div>
</div>
<div style={{flex:'1 0 200px'}}> {result}</div>
</div>
)
}
NavLink实现导航
//h5部分
<ul className="nav navbar-nav">
<NavLink className="navigation" to="/home">主页 </NavLink>
<NavLink className="navigation" to="/about">关于我们</NavLink>
</ul>
//css部分
a:focus,a.active{
color:rgb(108, 108, 108);
text-decoration: none;
}
a:hover{
color:rgb(172, 145, 145);
text-decoration: none;
}