rendering_lists.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #![allow(non_snake_case)]
  2. use dioxus::prelude::*;
  3. fn main() {
  4. dioxus::desktop::launch(App);
  5. }
  6. #[derive(PartialEq, Clone)]
  7. struct Comment {
  8. content: String,
  9. id: usize,
  10. }
  11. pub fn App(cx: Scope) -> Element {
  12. // ANCHOR: render_list
  13. let comment_field = use_state(&cx, || String::new());
  14. let mut next_id = use_state(&cx, || 0);
  15. let comments = use_ref(&cx, || Vec::<Comment>::new());
  16. let comments_lock = comments.read();
  17. let comments_rendered = comments_lock.iter().map(|comment| {
  18. cx.render(rsx!(CommentComponent {
  19. key: "{comment.id}",
  20. comment: comment.clone(),
  21. }))
  22. });
  23. cx.render(rsx!(
  24. form {
  25. onsubmit: move |_| {
  26. comments.write().push(Comment {
  27. content: comment_field.get().clone(),
  28. id: *next_id.get(),
  29. });
  30. next_id += 1;
  31. comment_field.set(String::new());
  32. },
  33. input {
  34. value: "{comment_field}",
  35. oninput: |event| comment_field.set(event.value.clone()),
  36. }
  37. input {
  38. r#type: "submit",
  39. }
  40. },
  41. comments_rendered,
  42. ))
  43. // ANCHOR_END: render_list
  44. }
  45. #[inline_props]
  46. fn CommentComponent(cx: Scope, comment: Comment) -> Element {
  47. cx.render(rsx!(div {
  48. "Comment by anon:",
  49. p { "{comment.content}" }
  50. button { "Reply" },
  51. }))
  52. }