listener.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. fn main() {}
  9. /// We can use `set_name` in multiple closures; the closures automatically *copy* the reference to set_name.
  10. static ButtonList: FC<()> = |cx| {
  11. let name = use_state(cx, || "...?");
  12. let names = ["jack", "jill", "john", "jane"]
  13. .iter()
  14. .map(move |n| rsx!(button { onclick: move |_| name.set(n), "{n}" }));
  15. cx.render(rsx!(
  16. div {
  17. h1 { "Hello, {name}" }
  18. {names}
  19. }
  20. ))
  21. };
  22. /// This shows how listeners may be without a visible change in the display.
  23. /// Check the console.
  24. static NonUpdatingEvents: FC<()> = |cx| {
  25. rsx!(in cx, div {
  26. button {
  27. onclick: move |_| log::info!("Did not cause any updates!")
  28. "Click me to log!"
  29. }
  30. })
  31. };
  32. static DisablePropogation: FC<()> = |cx| {
  33. rsx!(in cx,
  34. div {
  35. onclick: move |_| log::info!("event propogated to the div!")
  36. button {
  37. onclick: move |evt| {
  38. log::info!("Button will allow propogation");
  39. }
  40. }
  41. }
  42. )
  43. };