borrowed.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. ));
  35. }
  36. root.finish()
  37. }))
  38. }
  39. // props should derive a partialeq implementation automatically, but implement ptr compare for & fields
  40. #[derive(Props)]
  41. struct ChildProps<'a> {
  42. // Pass down complex structs
  43. item: &'a ListItem,
  44. // Even pass down handlers!
  45. item_handler: &'a dyn Fn(i32),
  46. }
  47. impl PartialEq for ChildProps<'_> {
  48. fn eq(&self, _other: &Self) -> bool {
  49. false
  50. }
  51. }
  52. fn ChildItem<'a>(ctx: Context<'a>, props: &ChildProps) -> DomTree {
  53. ctx.render(rsx! {
  54. div {
  55. onclick: move |evt| (props.item_handler)(10)
  56. h1 { "abcd123" }
  57. h2 { "abcd123" }
  58. div {
  59. "abcd123"
  60. h2 { }
  61. p { }
  62. }
  63. }
  64. })
  65. }