borrowed.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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, ops::Deref, rc::Rc};
  9. use dioxus_core::prelude::*;
  10. struct Props {
  11. items: Vec<Rc<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.clone())
  32. .item_handler(Callback(set_val.clone()))
  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, PartialEq)]
  42. struct ChildProps {
  43. // Pass down complex structs
  44. item: Rc<ListItem>,
  45. // Even pass down handlers!
  46. item_handler: Callback<i32>,
  47. }
  48. fn ChildItem<'a>(ctx: Context<'a>, props: &ChildProps) -> DomTree {
  49. ctx.render(rsx! {
  50. div {
  51. onclick: move |evt| (props.item_handler)(10)
  52. h1 { "abcd123" }
  53. h2 { "abcd123" }
  54. div {
  55. "abcd123"
  56. h2 { }
  57. p { }
  58. }
  59. }
  60. })
  61. }
  62. #[derive(Clone)]
  63. struct Callback<I, O = ()>(Rc<dyn Fn(I) -> O>);
  64. impl<I, O> Deref for Callback<I, O> {
  65. type Target = Rc<dyn Fn(I) -> O>;
  66. fn deref(&self) -> &Self::Target {
  67. &self.0
  68. }
  69. }
  70. impl<I, O> PartialEq for Callback<I, O> {
  71. fn eq(&self, other: &Self) -> bool {
  72. Rc::ptr_eq(&self.0, &other.0)
  73. }
  74. }