高階コンポーネント
構造体コンポーネントが機能を直接サポートしない場合 (例: サスペンス) または機能を使用するために大量のボイラープレートコードを必要とする場合 (例: コンテキスト) がいくつかあります。
そのような場合は、高階コンポーネントである関数コンポーネントを作成することをお勧めします。
高階コンポーネントの定義
高階コンポーネントは、新しい HTML を追加せず、他のコンポーネントをラップして追加の機能を提供するコンポーネントです。
例
コンテキストに接続して構造体コンポーネントに引き渡します
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>
}
}
}