dioxus/packages/core/examples/borrowed.rs

77 lines
2 KiB
Rust
Raw Normal View History

//! Demonstrate that borrowed data is possible as a property type
//! Borrowing (rather than cloning) is very important for speed and ergonomics.
2021-02-22 18:10:36 +00:00
//!
//! It's slightly more advanced than just cloning, but well worth the investment.
//!
//! If you use the FC macro, we handle the lifetimes automatically, making it easy to write efficient & performant components.
fn main() {}
2021-03-26 19:50:28 +00:00
use std::borrow::Borrow;
2021-03-09 19:45:52 +00:00
use dioxus_core::prelude::*;
struct Props {
items: Vec<ListItem>,
}
#[derive(PartialEq)]
struct ListItem {
name: String,
age: u32,
}
2021-03-26 19:50:28 +00:00
fn app<'a>(ctx: Context<'a>, props: &Props) -> DomTree {
let val = use_state(&ctx, || 0);
2021-03-01 02:21:17 +00:00
ctx.render(dioxus::prelude::LazyNodes::new(move |c| {
let mut root = builder::ElementBuilder::new(c, "div");
for child in &props.items {
// notice that the child directly borrows from our vec
// this makes lists very fast (simply views reusing lifetimes)
// <ChildItem item=child hanldler=setter />
root = root.child(builder::virtual_child(
c,
2021-03-09 19:45:52 +00:00
ChildItem,
// create the props with nothing but the fc<T>
fc_to_builder(ChildItem)
.item(child)
2021-03-26 19:50:28 +00:00
.item_handler(val.setter())
2021-03-09 19:45:52 +00:00
.build(),
));
}
root.finish()
}))
}
// props should derive a partialeq implementation automatically, but implement ptr compare for & fields
#[derive(Props)]
struct ChildProps<'a> {
2021-03-01 02:21:17 +00:00
// Pass down complex structs
item: &'a ListItem,
2021-03-01 02:21:17 +00:00
// Even pass down handlers!
2021-03-26 19:50:28 +00:00
item_handler: &'a dyn Fn(i32),
}
impl PartialEq for ChildProps<'_> {
2021-03-11 00:42:31 +00:00
fn eq(&self, _other: &Self) -> bool {
2021-03-09 19:45:52 +00:00
false
}
}
2021-03-26 19:50:28 +00:00
fn ChildItem<'a>(ctx: Context<'a>, props: &ChildProps) -> DomTree {
2021-03-01 02:21:17 +00:00
ctx.render(rsx! {
div {
2021-03-26 19:50:28 +00:00
onclick: move |evt| (props.item_handler)(10)
h1 { "abcd123" }
h2 { "abcd123" }
2021-03-01 02:21:17 +00:00
div {
2021-03-26 19:50:28 +00:00
"abcd123"
h2 { }
p { }
}
2021-03-01 02:21:17 +00:00
}
})
}