borrowed.rs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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(ctx: Context<Props>) -> VNode {
  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 &ctx.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. }
  38. root.finish()
  39. }))
  40. }
  41. // props should derive a partialeq implementation automatically, but implement ptr compare for & fields
  42. #[derive(Props, PartialEq)]
  43. struct ChildProps {
  44. // Pass down complex structs
  45. item: Rc<ListItem>,
  46. // Even pass down handlers!
  47. item_handler: Callback<i32>,
  48. }
  49. fn ChildItem<'a>(ctx: Context<ChildProps>) -> VNode {
  50. ctx.render(rsx! {
  51. div {
  52. // onclick: move |evt| (ctx.item_handler)(10)
  53. h1 { "abcd123 {ctx.item.name}" }
  54. h2 { "abcd123" }
  55. div {
  56. "abcd123"
  57. h2 { }
  58. p { }
  59. }
  60. }
  61. })
  62. }
  63. #[derive(Clone)]
  64. struct Callback<I, O = ()>(Rc<dyn Fn(I) -> O>);
  65. impl<I, O> Deref for Callback<I, O> {
  66. type Target = Rc<dyn Fn(I) -> O>;
  67. fn deref(&self) -> &Self::Target {
  68. &self.0
  69. }
  70. }
  71. impl<I, O> PartialEq for Callback<I, O> {
  72. fn eq(&self, other: &Self) -> bool {
  73. Rc::ptr_eq(&self.0, &other.0)
  74. }
  75. }