Browse Source

Make the function bounds for map less restrictive

Evan Almloff 1 năm trước cách đây
mục cha
commit
a2fadc8d11

+ 28 - 0
packages/signals/examples/iterator.rs

@@ -0,0 +1,28 @@
+use dioxus::prelude::*;
+use dioxus_signals::*;
+
+fn main() {
+    dioxus_desktop::launch(App);
+}
+
+#[component]
+fn App(cx: Scope) -> Element {
+    let signal = use_signal(cx, || vec![String::from("Hello"), String::from("World")]);
+
+    render! {
+        button {
+            onclick: move |_| {
+                signal.write().push(String::from("Hello"));
+            },
+            "Add one"
+        }
+        for i in 0..signal().len() {
+            Child { signal: signal.map(move |v| v.get(i).unwrap()) }
+        }
+    }
+}
+
+#[component]
+fn Child(cx: Scope, signal: SignalMap<String>) -> Element {
+    render! {"{signal:?}"}
+}

+ 1 - 1
packages/signals/src/map.rs

@@ -13,7 +13,7 @@ pub struct SignalMap<U: 'static + ?Sized> {
 
 impl<U: ?Sized> SignalMap<U> {
     /// Create a new mapped signal.
-    pub fn new<T: 'static>(signal: Signal<T>, mapping: fn(&T) -> &U) -> Self {
+    pub fn new<T: 'static>(signal: Signal<T>, mapping: impl Fn(&T) -> &U + 'static) -> Self {
         Self {
             origin_scope: signal.origin_scope(),
             mapping: CopyValue::new(Box::new(move || Ref::map(signal.read(), |v| (mapping)(v)))),

+ 1 - 1
packages/signals/src/signal.rs

@@ -257,7 +257,7 @@ impl<T: 'static> Signal<T> {
     }
 
     /// Map the signal to a new type.
-    pub fn map<O>(self, f: fn(&T) -> &O) -> SignalMap<O> {
+    pub fn map<O>(self, f: impl Fn(&T) -> &O + 'static) -> SignalMap<O> {
         SignalMap::new(self, f)
     }
 }