Ver código fonte

Merge branches 'masenf/pyi-handle-callable', 'masenf/merge-var-data-hooks-first' and 'masenf/component-pass-ref' into masenf/react-dnd-integ

Masen Furer 2 semanas atrás
pai
commit
5f8876528a

+ 7 - 3
reflex/components/component.py

@@ -280,6 +280,9 @@ class Component(BaseComponent, ABC):
     # The id for the component.
     id: Any = pydantic.v1.Field(default_factory=lambda: None)
 
+    # The Var to pass as the ref to the component.
+    ref: Var | None = pydantic.v1.Field(default_factory=lambda: None)
+
     # The class name for the component.
     class_name: Any = pydantic.v1.Field(default_factory=lambda: None)
 
@@ -709,9 +712,10 @@ class Component(BaseComponent, ABC):
                 attr.removesuffix("_"): getattr(self, attr) for attr in self.get_props()
             }
 
-            # Add ref to element if `id` is not None.
-            ref = self.get_ref()
-            if ref is not None:
+            # Add ref to element if `ref` is None and `id` is not None.
+            if self.ref is not None:
+                props["ref"] = self.ref
+            elif (ref := self.get_ref()) is not None:
                 props["ref"] = Var(_js_expr=ref)
         else:
             props = props.copy()

+ 2 - 1
reflex/vars/base.py

@@ -170,7 +170,8 @@ class VarData:
         object.__setattr__(self, "components", tuple(components or []))
 
         if hooks and any(hooks.values()):
-            merged_var_data = VarData.merge(self, *hooks.values())
+            # Merge our dependencies first, so they can be referenced.
+            merged_var_data = VarData.merge(*hooks.values(), self)
             if merged_var_data is not None:
                 object.__setattr__(self, "state", merged_var_data.state)
                 object.__setattr__(self, "field_name", merged_var_data.field_name)

+ 12 - 0
tests/units/components/test_component.py

@@ -2335,3 +2335,15 @@ def test_special_props(component_kwargs, exp_custom_attrs, exp_style):
     for prop in SpecialComponent.get_props():
         if prop in component_kwargs:
             assert getattr(component, prop)._var_value == component_kwargs[prop]
+
+
+def test_ref():
+    """Test that the ref prop is correctly added to the component."""
+    custom_ref = Var("custom_ref")
+    ref_component = rx.box(ref=custom_ref)
+    assert ref_component._render().props["ref"].equals(custom_ref)
+
+    id_component = rx.box(id="custom_id")
+    assert id_component._render().props["ref"].equals(Var("ref_custom_id"))
+
+    assert "ref" not in rx.box()._render().props

+ 1 - 1
tests/units/test_var.py

@@ -1896,7 +1896,7 @@ def test_var_data_hooks():
 
 def test_var_data_with_hooks_value():
     var_data = VarData(hooks={"what": VarData(hooks={"whot": VarData(hooks="whott")})})
-    assert var_data == VarData(hooks=["what", "whot", "whott"])
+    assert var_data == VarData(hooks=["whott", "whot", "what"])
 
 
 def test_str_var_in_components(mocker):