event_handler.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use dioxus::prelude::*;
  2. // This test just checks that event handlers compile without explicit type annotations
  3. // It will not actually run any code
  4. #[test]
  5. #[allow(unused)]
  6. fn event_handlers_compile() {
  7. fn app() -> Element {
  8. let mut todos = use_signal(String::new);
  9. rsx! {
  10. input {
  11. // Normal event handlers work without explicit type annotations
  12. oninput: move |evt| todos.set(evt.value()),
  13. }
  14. button {
  15. // async event handlers work without explicit type annotations
  16. onclick: |event| async move {
  17. println!("{event:?}");
  18. },
  19. }
  20. // New! You can now use async closures for custom event handlers!
  21. // This shouldn't require an explicit type annotation
  22. TakesEventHandler { onclick: |event| async move {
  23. println!("{event:?}");
  24. } }
  25. // Or you can accept a callback that returns a value
  26. // This shouldn't require an explicit type annotation
  27. TakesEventHandlerWithArg { double: move |value| (value * 2) as i32 }
  28. }
  29. }
  30. #[component]
  31. fn TakesEventHandler(onclick: EventHandler<MouseEvent>) -> Element {
  32. rsx! {
  33. button {
  34. // You can pass in EventHandlers directly to events
  35. onclick: onclick,
  36. "Click!"
  37. }
  38. button {
  39. // Or use the shorthand syntax
  40. onclick,
  41. "Click!"
  42. }
  43. // You should also be able to forward event handlers to other components with the shorthand syntax
  44. TakesEventHandler {
  45. onclick
  46. }
  47. }
  48. }
  49. #[component]
  50. fn TakesEventHandlerWithArg(double: Callback<u32, i32>) -> Element {
  51. let mut count = use_signal(|| 2);
  52. rsx! {
  53. button {
  54. // Callbacks let you easily inject custom logic into your components
  55. onclick: move |_| count.set(double(count()) as u32),
  56. "{count}"
  57. }
  58. }
  59. }
  60. }