borrowed.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //! Demonstrate that borrowed data is possible as a property type
  2. //! Borrowing (rather than cloning) is very important for speed and ergonomics.
  3. //!
  4. //! It's slightly more advanced than just cloning, but well worth the investment.
  5. //!
  6. //! If you use the FC macro, we handle the lifetimes automatically, making it easy to write efficient & performant components.
  7. fn main() {}
  8. use std::borrow::Borrow;
  9. use dioxus_core::prelude::*;
  10. struct Props {
  11. items: Vec<ListItem>,
  12. }
  13. #[derive(PartialEq)]
  14. struct ListItem {
  15. name: String,
  16. age: u32,
  17. }
  18. fn app<'a>(ctx: Context<'a>, props: &Props) -> DomTree {
  19. let (val, set_val) = use_state(&ctx, || 0);
  20. ctx.render(dioxus::prelude::LazyNodes::new(move |c| {
  21. let mut root = builder::ElementBuilder::new(c, "div");
  22. for child in &props.items {
  23. // notice that the child directly borrows from our vec
  24. // this makes lists very fast (simply views reusing lifetimes)
  25. // <ChildItem item=child hanldler=setter />
  26. root = root.child(builder::virtual_child(
  27. c,
  28. ChildItem,
  29. // create the props with nothing but the fc<T>
  30. fc_to_builder(ChildItem)
  31. .item(child)
  32. .item_handler(set_val)
  33. .build(),
  34. None,
  35. ));
  36. }
  37. root.finish()
  38. }))
  39. }
  40. // props should derive a partialeq implementation automatically, but implement ptr compare for & fields
  41. #[derive(Props)]
  42. struct ChildProps<'a> {
  43. // Pass down complex structs
  44. item: &'a ListItem,
  45. // Even pass down handlers!
  46. item_handler: &'a dyn Fn(i32),
  47. }
  48. impl PartialEq for ChildProps<'_> {
  49. fn eq(&self, _other: &Self) -> bool {
  50. false
  51. }
  52. }
  53. fn ChildItem<'a>(ctx: Context<'a>, props: &ChildProps) -> DomTree {
  54. ctx.render(rsx! {
  55. div {
  56. onclick: move |evt| (props.item_handler)(10)
  57. h1 { "abcd123" }
  58. h2 { "abcd123" }
  59. div {
  60. "abcd123"
  61. h2 { }
  62. p { }
  63. }
  64. }
  65. })
  66. }