borrowed.rs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 dioxus_core::prelude::*;
  9. use std::rc::Rc;
  10. struct AppProps {
  11. items: Vec<Rc<ListItem>>,
  12. }
  13. #[derive(PartialEq)]
  14. struct ListItem {
  15. name: String,
  16. age: u32,
  17. }
  18. fn app(ctx: Context<AppProps>) -> VNode {
  19. let (val, set_val) = use_state(&ctx, || 0);
  20. ctx.render(LazyNodes::new(move |_nodectx| {
  21. builder::ElementBuilder::new(_nodectx, "div")
  22. .iter_child({
  23. ctx.items.iter().map(|child| {
  24. builder::virtual_child(
  25. _nodectx,
  26. ChildItem,
  27. ChildProps {
  28. item: child.clone(),
  29. item_handler: set_val.clone(),
  30. },
  31. None,
  32. &[],
  33. )
  34. })
  35. })
  36. .iter_child([builder::ElementBuilder::new(_nodectx, "div")
  37. .iter_child([builder::text3(_nodectx.bump(), format_args!("{}", val))])
  38. .finish()])
  39. .finish()
  40. }))
  41. }
  42. // props should derive a partialeq implementation automatically, but implement ptr compare for & fields
  43. struct ChildProps {
  44. // Pass down complex structs
  45. item: Rc<ListItem>,
  46. // Even pass down handlers!
  47. item_handler: Rc<dyn Fn(i32)>,
  48. }
  49. fn ChildItem<'a>(cx: Context<'a, ChildProps>) -> VNode {
  50. cx.render(LazyNodes::new(move |__cx| todo!()))
  51. }
  52. impl PartialEq for ChildProps {
  53. fn eq(&self, other: &Self) -> bool {
  54. false
  55. }
  56. }
  57. unsafe impl Properties for ChildProps {
  58. type Builder = ();
  59. const CAN_BE_MEMOIZED: bool = false;
  60. fn builder() -> Self::Builder {
  61. ()
  62. }
  63. }