mirror of
https://github.com/yewstack/yew.git
synced 2025-12-08 21:26:25 +00:00
* 0.20 Changelog * Improve changelog generator * Add blog post * Add blog post * Apply suggestions from code review Co-authored-by: WorldSEnder <WorldSEnder@users.noreply.github.com> Co-authored-by: Julius Lungys <32368314+voidpumpkin@users.noreply.github.com> * update Changelog * update Cargo.toml * changelog gen compiles * website version 0.20 * add migration guides * prettier * i18n Co-authored-by: WorldSEnder <WorldSEnder@users.noreply.github.com> Co-authored-by: Julius Lungys <32368314+voidpumpkin@users.noreply.github.com>
83 lines
1.8 KiB
Plaintext
83 lines
1.8 KiB
Plaintext
---
|
|
title: 'Higher Order Components'
|
|
---
|
|
|
|
There are several cases where Struct components dont directly support a feature (ex. Suspense) or require a lot of boiler plate to use the features (ex. Context).
|
|
|
|
In those cases it is recommended to create function components that are higher order components.
|
|
|
|
## Higher Order Components Definition
|
|
|
|
Higher Order Components are components that dont add any new Html and only wrap some other component to provide extra functionality.
|
|
|
|
### Example
|
|
|
|
Hook into Context and pass it down to a struct component
|
|
|
|
```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>
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
```
|