spreadpattern.rs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //! Example: Spread pattern for Components
  2. //! --------------------------------------
  3. //!
  4. //! Dioxus supports the "spread" pattern for manually building a component's properties. This is useful when props
  5. //! are passed down from a parent, or it's more ergonomic to construct props from outside the rsx! macro.
  6. //!
  7. //! To use the spread pattern, simply pass ".." followed by a Rust expression. This pattern also supports overriding
  8. //! values, using the manual props as the base and then modifying fields specified with non-spread attributes.
  9. use dioxus::prelude::*;
  10. pub fn Example(cx: Scope) -> Element {
  11. let props = MyProps {
  12. count: 0,
  13. live: true,
  14. name: "Dioxus",
  15. };
  16. cx.render(rsx! {
  17. Example1 { ..props, count: 10, div {"child"} }
  18. })
  19. }
  20. #[derive(Props)]
  21. pub struct MyProps<'a> {
  22. count: u32,
  23. live: bool,
  24. name: &'static str,
  25. children: Element<'a>,
  26. }
  27. pub fn Example1<'a>(cx: Scope<'a, MyProps<'a>>) -> Element {
  28. let MyProps { count, live, name } = cx.props;
  29. cx.render(rsx! {
  30. div {
  31. h1 { "Hello, {name}"}
  32. h3 {"Are we alive? {live}"}
  33. p {"Count is {count}"}
  34. &cx.props.children
  35. }
  36. })
  37. }