Răsfoiți Sursa

feature: support custom attribute for components (#1085)

TaiJuWu 2 ani în urmă
părinte
comite
0531d611dc
2 a modificat fișierele cu 15 adăugiri și 0 ștergeri
  1. 5 0
      pynecone/components/component.py
  2. 10 0
      tests/components/test_component.py

+ 5 - 0
pynecone/components/component.py

@@ -66,6 +66,8 @@ class Component(Base, ABC):
 
 
     # components that cannot be children
     # components that cannot be children
     invalid_children: List[str] = []
     invalid_children: List[str] = []
+    # custom attribute
+    custom_attrs: Dict[str, str] = {}
 
 
     @classmethod
     @classmethod
     def __init_subclass__(cls, **kwargs):
     def __init_subclass__(cls, **kwargs):
@@ -181,6 +183,8 @@ class Component(Base, ABC):
                 **{attr: value for attr, value in kwargs.items() if attr not in fields},
                 **{attr: value for attr, value in kwargs.items() if attr not in fields},
             }
             }
         )
         )
+        if "custom_attrs" not in kwargs:
+            kwargs["custom_attrs"] = {}
 
 
         # Convert class_name to str if it's list
         # Convert class_name to str if it's list
         class_name = kwargs.get("class_name", "")
         class_name = kwargs.get("class_name", "")
@@ -436,6 +440,7 @@ class Component(Base, ABC):
                 sx=self.style,
                 sx=self.style,
                 id=self.id,
                 id=self.id,
                 class_name=self.class_name,
                 class_name=self.class_name,
+                **self.custom_attrs,
             ).set(
             ).set(
                 children=[child.render() for child in self.children],
                 children=[child.render() for child in self.children],
                 contents=str(tag.contents),
                 contents=str(tag.contents),

+ 10 - 0
tests/components/test_component.py

@@ -181,6 +181,16 @@ def test_set_style_attrs(component1):
     assert component.style["textAlign"] == "center"
     assert component.style["textAlign"] == "center"
 
 
 
 
+def test_custom_attrs(component1):
+    """Test that custom attributes are set in the dict.
+
+    Args:
+        component1: A test component.
+    """
+    component = component1(custom_attrs={"attr1": "1", "attr2": "attr2"})
+    assert component.custom_attrs == {"attr1": "1", "attr2": "attr2"}
+
+
 def test_create_component(component1):
 def test_create_component(component1):
     """Test that the component is created correctly.
     """Test that the component is created correctly.