如何添加.is-active css类时,点击路由链接?



这是yew中的一个简单的bulma css navbar。我的问题是如何添加.is-active类的"导航栏项目"时,通过点击路由链接导航?

看起来我必须在这里使用一些有状态的utils。但是我无法拦截路由链接中的onclick事件。

use yew::prelude::*;
use yew_router::prelude::*;
use crate::routes::app_routes::AppRoutes;
#[function_component]
pub fn Nav() -> Html {
let navbar_active = use_state_eq(|| false);
let toggle_navbar = {
let navbar_active = navbar_active.clone();
Callback::from(move |_| {
navbar_active.set(!*navbar_active);
})
};
let active_class = if !*navbar_active { "is-active" } else { "" };
html! {
<nav class="navbar is-primary" role="navigation" aria-label="main navigation">
<div class="navbar-brand">
<h1 class="navbar-item is-size-3">{ "UVW" }</h1>
<button class={classes!("navbar-burger", "burger", active_class)}
aria-label="menu" aria-expanded="false"
onclick={toggle_navbar}
>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</button>
</div>
<div class={classes!("navbar-menu", active_class)}>
<div class="navbar-start">
<Link<AppRoutes> classes={classes!("navbar-item")} to={AppRoutes::Home}>
{ "Home" }
</Link<AppRoutes>>
<Link<AppRoutes> classes={classes!("navbar-item")} to={AppRoutes::About}>
{ "About" }
</Link<AppRoutes>>
<div class="navbar-item has-dropdown is-hoverable">
<div class="navbar-link">
{ "More" }
</div>
<div class="navbar-dropdown">
<Link<AppRoutes> classes={classes!("navbar-item")} to={AppRoutes::Home}>
{ "DropDown1" }
</Link<AppRoutes>>
<Link<AppRoutes> classes={classes!("navbar-item")} to={AppRoutes::Home}>
{ "DropDown2" }
</Link<AppRoutes>>
<Link<AppRoutes> classes={classes!("navbar-item")} to={AppRoutes::Home}>
{ "DropDown3" }
</Link<AppRoutes>>
</div>
</div>
</div>
</div>
</nav>
}
}

我没有找到任何"官方的";这样做。但一个可能的解决方案是用use_route钩入路由,并与之匹配。

我通过创建自己的fn组件来简化它,该组件检查它是否是当前路由。

#[derive(Properties, PartialEq)]
pub struct Props {
pub children: Children,
pub to: Route,
}
#[function_component(RouteLink)]
fn route_link(props: &Props) -> Html {
let route = use_route::<Route>().unwrap_or_default();
let classes = if route == props.to {
classes!("text-gray-900")
} else {
classes!("text-gray-400")
};
html! {
<Link<Route> classes={classes} to={props.to.clone()}>{for props.children.iter() }</Link<Route>>
}
}

相关内容

  • 没有找到相关文章

最新更新