跳到主要內容
版本:0.21

高階元件

在某些情況下,結構元件不直接支援功能(例如 Suspense)或需要大量樣板代碼才能使用功能(例如 Context)。

在這些情況下,建議建立高階元件的函式元件。

高階元件定義

高階元件是不新增任何新的 HTML 且僅包覆一些其他元件以提供其他功能的元件。

範例

連接到 Context 並將其向下傳遞到結構元件

use yew::prelude::*;

#[derive(Clone, Debug, PartialEq)]
struct Theme {
foreground: String,
background: String,
}

#[function_component]
pub fn App() -> Html {
let ctx = use_state(|| Theme {
foreground: "#000000".to_owned(),
background: "#eeeeee".to_owned(),
});

html! {
<ContextProvider<Theme> context={(*ctx).clone()}>
<ThemedButtonHOC />
</ContextProvider<Theme>>
}
}

#[function_component]
pub fn ThemedButtonHOC() -> Html {
let theme = use_context::<Theme>().expect("no ctx found");

html! {<ThemedButtonStructComponent {theme} />}
}

#[derive(Properties, PartialEq)]
pub struct Props {
pub theme: Theme,
}

struct ThemedButtonStructComponent;

impl Component for ThemedButtonStructComponent {
type Message = ();
type Properties = Props;

fn create(_ctx: &Context<Self>) -> Self {
Self
}

fn view(&self, ctx: &Context<Self>) -> Html {
let theme = &ctx.props().theme;
html! {
<button style={format!(
"background: {}; color: {};",
theme.background,
theme.foreground
)}
>
{ "Click me!" }
</button>
}
}
}