dioxus/examples/core_reference/spreadpattern.rs

42 lines
1.2 KiB
Rust
Raw Normal View History

2021-07-02 05:30:52 +00:00
//! Example: Spread pattern for Components
//! --------------------------------------
//!
2021-10-24 17:30:36 +00:00
//! Dioxus supports the "spread" pattern for manually building a component's properties. This is useful when props
2021-07-02 05:30:52 +00:00
//! are passed down from a parent, or it's more ergonomic to construct props from outside the rsx! macro.
//!
2021-10-24 17:30:36 +00:00
//! To use the spread pattern, simply pass ".." followed by a Rust expression. This pattern also supports overriding
2021-07-02 05:30:52 +00:00
//! values, using the manual props as the base and then modifying fields specified with non-spread attributes.
use dioxus::prelude::*;
pub fn Example(cx: Scope) -> Element {
2021-07-02 05:30:52 +00:00
let props = MyProps {
count: 0,
live: true,
name: "Dioxus",
};
cx.render(rsx! {
2021-07-16 20:11:25 +00:00
Example1 { ..props, count: 10, div {"child"} }
2021-07-02 05:30:52 +00:00
})
}
2021-07-02 05:30:52 +00:00
#[derive(Props)]
pub struct MyProps<'a> {
2021-07-02 05:30:52 +00:00
count: u32,
live: bool,
name: &'static str,
children: Element<'a>,
2021-07-02 05:30:52 +00:00
}
2022-01-03 18:26:15 +00:00
pub fn Example1<'a>(cx: Scope<'a, MyProps<'a>>) -> Element {
let MyProps { count, live, name } = cx.props;
2021-07-02 05:30:52 +00:00
cx.render(rsx! {
div {
2021-09-21 17:42:52 +00:00
h1 { "Hello, {name}"}
h3 {"Are we alive? {live}"}
p {"Count is {count}"}
&cx.props.children
2021-07-02 05:30:52 +00:00
}
})
}