props_safety.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. use dioxus::prelude::*;
  2. fn main() {
  3. dioxus_desktop::launch(app);
  4. }
  5. fn app(cx: Scope) -> Element {
  6. let count: &RefCell<Vec<&Element>> = cx.use_hook(|| RefCell::new(Vec::new()));
  7. let element = render! {
  8. div {
  9. "hello world!"
  10. }
  11. };
  12. let nested_borrows = cx.use_hook(Vec::new);
  13. nested_borrows.push("hello world!");
  14. cx.render(rsx! {
  15. // unsafe_child_component {
  16. // borrowed: count
  17. // }
  18. safe_child_component {
  19. borrowed: element
  20. }
  21. safe_nested_borrows {
  22. borrowed: &**nested_borrows
  23. }
  24. })
  25. }
  26. #[derive(Props)]
  27. struct NestedBorrows<'a> {
  28. borrowed: &'a [&'a str],
  29. }
  30. fn safe_nested_borrows<'a>(cx: Scope<'a, NestedBorrows<'a>>) -> Element<'a> {
  31. render! {
  32. div { "{cx.props.borrowed:?}" }
  33. }
  34. }
  35. #[derive(Props)]
  36. struct Testing<'a> {
  37. borrowed: &'a RefCell<Vec<&'a Element<'a>>>,
  38. }
  39. fn unsafe_child_component<'a>(cx: Scope<'a, Testing<'a>>) -> Element<'a> {
  40. let Testing { borrowed } = cx.props;
  41. let borrowed = borrowed.borrow();
  42. cx.render(rsx! {
  43. div { "Hello, world!" }
  44. })
  45. }
  46. #[derive(Props)]
  47. struct SafeTesting<'a> {
  48. borrowed: Element<'a>,
  49. }
  50. fn safe_child_component<'a>(cx: Scope<'a, SafeTesting<'a>>) -> Element<'a> {
  51. let SafeTesting { borrowed } = cx.props;
  52. cx.render(rsx! {
  53. div {
  54. borrowed
  55. }
  56. })
  57. }