feat: Switch adds on_change prop (#196)

This commit is contained in:
luoxiaozero 2024-05-20 14:19:48 +08:00 committed by GitHub
parent ab3ea810de
commit 3266ac7068
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 24 additions and 6 deletions

View file

@ -3,14 +3,24 @@
```rust demo
let value = create_rw_signal(false);
let message = use_message();
let on_change = move |value: bool| {
message.create(
format!("{value}"),
MessageVariant::Success,
Default::default(),
);
};
view! {
<Switch value />
<Switch value on_change/>
}
```
### Switch Props
| Name | Type | Default | Description |
| ----- | ----------------------------------- | -------------------- | ----------------------------------------- |
| --------- | ----------------------------------- | -------------------- | ------------------------------------------- |
| class | `OptionalProp<MaybeSignal<String>>` | `Default::default()` | Addtional classes for the switch element. |
| value | `Model<bool>` | `false` | Switch's value. |
| on_change | `Option<Callback>` | `None` | Trigger when the checked state is changing. |

View file

@ -9,6 +9,7 @@ use thaw_utils::{class_list, mount_style, Model, OptionalProp};
#[component]
pub fn Switch(
#[prop(optional, into)] value: Model<bool>,
#[prop(optional, into)] on_change: Option<Callback<bool>>,
#[prop(optional, into)] class: OptionalProp<MaybeSignal<String>>,
) -> impl IntoView {
mount_style("switch", include_str!("./switch.css"));
@ -27,6 +28,13 @@ pub fn Switch(
});
css_vars
});
let on_click = move |_| {
let new_value = !value.get_untracked();
value.set(new_value);
if let Some(on_change) = on_change {
on_change.call(new_value);
}
};
view! {
<div
@ -36,7 +44,7 @@ pub fn Switch(
]
style=move || css_vars.get()
on:click=move |_| value.set(!value.get_untracked())
on:click=on_click
role="switch"
aria-checked=move || if value.get() { "true" } else { "false" }
>