add the methods and From impls (#3519)

This commit is contained in:
Tim Kurdov 2023-11-05 12:32:04 +00:00 committed by GitHub
parent 00a6183bd2
commit 8d2cfdee69
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 0 deletions

View File

@ -5,6 +5,8 @@ use std::ops::Deref;
use std::rc::Rc;
use crate::functional::{hook, Hook, HookContext};
use crate::html::IntoPropValue;
use crate::Callback;
type DispatchFn<T> = Rc<dyn Fn(<T as Reducible>::Action)>;
@ -133,6 +135,24 @@ where
}
}
impl<T> From<UseReducerDispatcher<T>> for Callback<<T as Reducible>::Action>
where
T: Reducible,
{
fn from(val: UseReducerDispatcher<T>) -> Self {
Callback { cb: val.dispatch }
}
}
impl<T> IntoPropValue<Callback<<T as Reducible>::Action>> for UseReducerDispatcher<T>
where
T: Reducible,
{
fn into_prop_value(self) -> Callback<<T as Reducible>::Action> {
Callback { cb: self.dispatch }
}
}
impl<T> UseReducerDispatcher<T>
where
T: Reducible,
@ -141,6 +161,14 @@ where
pub fn dispatch(&self, value: T::Action) {
(self.dispatch)(value)
}
/// Get a callback, invoking which is equivalent to calling `dispatch()`
/// on this same dispatcher.
pub fn to_callback(&self) -> Callback<<T as Reducible>::Action> {
Callback {
cb: self.dispatch.clone(),
}
}
}
/// The base function of [`use_reducer`] and [`use_reducer_eq`]

View File

@ -4,6 +4,8 @@ use std::rc::Rc;
use super::{use_reducer, use_reducer_eq, Reducible, UseReducerDispatcher, UseReducerHandle};
use crate::functional::hook;
use crate::html::IntoPropValue;
use crate::Callback;
struct UseStateReducer<T> {
value: T,
@ -171,6 +173,18 @@ where
}
}
impl<T> From<UseStateSetter<T>> for Callback<T> {
fn from(value: UseStateSetter<T>) -> Self {
Self::from(value.inner)
}
}
impl<T> IntoPropValue<Callback<T>> for UseStateSetter<T> {
fn into_prop_value(self) -> Callback<T> {
self.inner.into_prop_value()
}
}
impl<T> PartialEq for UseStateSetter<T> {
fn eq(&self, rhs: &Self) -> bool {
self.inner == rhs.inner
@ -182,4 +196,10 @@ impl<T> UseStateSetter<T> {
pub fn set(&self, value: T) {
self.inner.dispatch(value)
}
/// Get a callback, invoking which is equivalent to calling `set()`
/// on this same setter.
pub fn to_callback(&self) -> Callback<T> {
self.inner.to_callback()
}
}