listener.rs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //! Example: Listeners
  2. //! ------------------
  3. //!
  4. //! This example demonstrates the various ways listeners may be used in Dioxus.
  5. //! Listeners may be at most `FnMut` - but not `FnOnce`.
  6. //! Listeners may borrow the lifetime of cx (children and hooks), but not of local (stack) data.
  7. use dioxus::prelude::*;
  8. pub static Example: FC<()> = |(cx, props)| {
  9. cx.render(rsx! {
  10. ButtonList {}
  11. NonUpdatingEvents {}
  12. DisablePropogation {}
  13. })
  14. };
  15. /// We can use `set_name` in multiple closures; the closures automatically *copy* the reference to set_name.
  16. static ButtonList: FC<()> = |(cx, props)| {
  17. let name = use_state(cx, || "...?");
  18. let names = ["jack", "jill", "john", "jane"]
  19. .iter()
  20. .map(move |n| rsx!(button { onclick: move |_| name.set(n), "{n}" }));
  21. cx.render(rsx!(
  22. div {
  23. h1 { "Hello, {name}" }
  24. {names}
  25. }
  26. ))
  27. };
  28. /// This shows how listeners may be without a visible change in the display.
  29. /// Check the console.
  30. static NonUpdatingEvents: FC<()> = |(cx, props)| {
  31. rsx!(cx, div {
  32. button {
  33. onclick: move |_| log::info!("Did not cause any updates!")
  34. "Click me to log!"
  35. }
  36. })
  37. };
  38. static DisablePropogation: FC<()> = |(cx, props)| {
  39. rsx!(cx,
  40. div {
  41. onclick: move |_| log::info!("event propogated to the div!")
  42. button {
  43. onclick: move |evt| {
  44. log::info!("Button will allow propogation");
  45. }
  46. }
  47. }
  48. )
  49. };