rendering_lists.rs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. #[rustfmt::skip]
  12. pub fn App(cx: Scope) -> Element {
  13. // ANCHOR: render_list
  14. let comment_field = use_state(cx, String::new);
  15. let mut next_id = use_state(cx, || 0);
  16. let comments = use_ref(cx, Vec::<Comment>::new);
  17. let comments_lock = comments.read();
  18. let comments_rendered = comments_lock.iter().map(|comment| {
  19. rsx!(CommentComponent {
  20. key: "{comment.id}",
  21. comment: comment.clone(),
  22. })
  23. });
  24. cx.render(rsx!(
  25. form {
  26. onsubmit: move |_| {
  27. comments.write().push(Comment {
  28. content: comment_field.get().clone(),
  29. id: *next_id.get(),
  30. });
  31. next_id += 1;
  32. comment_field.set(String::new());
  33. },
  34. input {
  35. value: "{comment_field}",
  36. oninput: |event| comment_field.set(event.value.clone()),
  37. }
  38. input {
  39. r#type: "submit",
  40. }
  41. },
  42. comments_rendered,
  43. ))
  44. // ANCHOR_END: render_list
  45. }
  46. #[rustfmt::skip]
  47. pub fn AppForLoop(cx: Scope) -> Element {
  48. // ANCHOR: render_list_for_loop
  49. let comment_field = use_state(cx, String::new);
  50. let mut next_id = use_state(cx, || 0);
  51. let comments = use_ref(cx, Vec::<Comment>::new);
  52. cx.render(rsx!(
  53. form {
  54. onsubmit: move |_| {
  55. comments.write().push(Comment {
  56. content: comment_field.get().clone(),
  57. id: *next_id.get(),
  58. });
  59. next_id += 1;
  60. comment_field.set(String::new());
  61. },
  62. input {
  63. value: "{comment_field}",
  64. oninput: |event| comment_field.set(event.value.clone()),
  65. }
  66. input {
  67. r#type: "submit",
  68. }
  69. },
  70. for comment in &*comments.read() {
  71. // Notice the body of this for loop is rsx code, not an expression
  72. CommentComponent {
  73. key: "{comment.id}",
  74. comment: comment.clone(),
  75. }
  76. }
  77. ))
  78. // ANCHOR_END: render_list_for_loop
  79. }
  80. #[inline_props]
  81. fn CommentComponent(cx: Scope, comment: Comment) -> Element {
  82. cx.render(rsx!(div {
  83. "Comment by anon:",
  84. p { "{comment.content}" }
  85. button { "Reply" },
  86. }))
  87. }