如何将路由定义为组件的道具 |红豆杉路线
How to define route as a prop to a component | yew-route
我定义了以下路由。
#[derive(Routable, PartialEq, Debug, Clone)]
pub enum Route {
#[at("/")]
Index,
#[at("about")]
About,
#[at("/contact")]
Contact,
#[at("/portfolio")]
Portfolio,
#[at("*")]
NotFound,
}
我想传递一个路由,例如 Route::Index
到下面的组件,但是有一个错误,如评论中所示
#[derive(Properties, PartialEq)]
pub struct IconProps {
pub route: Route,
pub alt: String,
pub icon_name: String,
}
#[function_component(Icon)]
pub fn icon(props: &IconProps) -> Html {
let src = format!("assets/icons/{}.svg", props.icon_name);
html! {
<div class={classes!("p-2", "mx-2", "my-1", "bg-green-100", "inline-block")}>
<Link<Route> classes={classes!("w-10", "h-10")} to={props.route}>
^^^^^^^^^^^^^^
// Diagnostics:
// 1. cannot move out of `props.route` which is behind a shared reference
// move occurs because `props.route` has type `Route`, which does not implement the `Copy` trait
<img
src={src}
alt={props.alt.to_owned()}
class={classes!("w-10", "h-10")}
/>
</Link<Route>>
</div>
}
}
那么,如何将路由作为道具呢?
好吧,我想解决方案有些明显。只需将 Copy
特征添加到 enum
#[derive(Routable, PartialEq, Debug, Clone, Copy)]
pub enum Route {
#[at("/")]
Index,
#[at("about")]
About,
#[at("/contact")]
Contact,
#[at("/portfolio")]
Portfolio,
#[at("*")]
NotFound,
}
我定义了以下路由。
#[derive(Routable, PartialEq, Debug, Clone)]
pub enum Route {
#[at("/")]
Index,
#[at("about")]
About,
#[at("/contact")]
Contact,
#[at("/portfolio")]
Portfolio,
#[at("*")]
NotFound,
}
我想传递一个路由,例如 Route::Index
到下面的组件,但是有一个错误,如评论中所示
#[derive(Properties, PartialEq)]
pub struct IconProps {
pub route: Route,
pub alt: String,
pub icon_name: String,
}
#[function_component(Icon)]
pub fn icon(props: &IconProps) -> Html {
let src = format!("assets/icons/{}.svg", props.icon_name);
html! {
<div class={classes!("p-2", "mx-2", "my-1", "bg-green-100", "inline-block")}>
<Link<Route> classes={classes!("w-10", "h-10")} to={props.route}>
^^^^^^^^^^^^^^
// Diagnostics:
// 1. cannot move out of `props.route` which is behind a shared reference
// move occurs because `props.route` has type `Route`, which does not implement the `Copy` trait
<img
src={src}
alt={props.alt.to_owned()}
class={classes!("w-10", "h-10")}
/>
</Link<Route>>
</div>
}
}
那么,如何将路由作为道具呢?
好吧,我想解决方案有些明显。只需将 Copy
特征添加到 enum
#[derive(Routable, PartialEq, Debug, Clone, Copy)]
pub enum Route {
#[at("/")]
Index,
#[at("about")]
About,
#[at("/contact")]
Contact,
#[at("/portfolio")]
Portfolio,
#[at("*")]
NotFound,
}