yew/website/i18n/ja/docusaurus-plugin-content-docs/version-0.22/advanced-topics/struct-components/hoc.mdx

83 lines
2.0 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: '高階コンポーネント'
---
いくつかの状況では、構造コンポーネントは特定の機能(例えば Suspenseを直接サポートしていないか、または特定の機能を使用するために大量のボイラープレートコードが必要です例えば Context
このような場合、高階コンポーネントの関数コンポーネントを作成することをお勧めします。
## 高階コンポーネントの定義
高階コンポーネントは、新しい HTML を追加せず、他のコンポーネントをラップして追加機能を提供するコンポーネントです。
### 例
Contextコンテキストフックを使用し、それを構造コンポーネントに渡す例
```rust
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>>
}
}
// highlight-start
#[function_component]
pub fn ThemedButtonHOC() -> Html {
let theme = use_context::<Theme>().expect("no ctx found");
html! {<ThemedButtonStructComponent {theme} />}
}
// highlight-end
#[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>
}
}
}
```