Component State
New in version 0.4.6.
Defining a subclass of rx.ComponentState
creates a special type of state that is tied to an
instance of a component, rather than existing globally in the app. A Component State combines
UI code with state Vars and
Event Handlers,
and is useful for creating reusable components which operate independently of each other.
Using ComponentState
0
0
0
The vars and event handlers defined on the ReusableCounter
class are treated similarly to a normal State class, but will be scoped to the component instance. Each time a
reusable_counter
is created, a new state class for that instance of the component is also created.
The get_component
classmethod is used to define the UI for the component and link it up to the State, which
is accessed via the cls
argument. Other states may also be referenced by the returned component, but
cls
will always be the instance of the ComponentState
that is unique to the component being returned.
Passing Props
Similar to a normal Component, the ComponentState.create
classmethod accepts the arbitrary
*children
and **props
arguments, and by default passes them to your get_component
classmethod.
These arguments may be used to customize the component, either by applying defaults or
passing props to certain subcomponents.
In the following example, we implement an editable text component that allows the user to click on
the text to turn it into an input field. If the user does not provide their own value
or on_change
props, then the defaults defined in the EditableText
class will be used.
Click to edit
Edit me!
Reflex is fun
Because this EditableText
component is designed to be reusable, it can handle the case
where the value
and on_change
are linked to a normal global state.
Global state text
GLOBAL STATE TEXT
Accessing the State
The underlying state class of a ComponentState
is accessible via the .State
attribute. To use it,
assign an instance of the component to a local variable, then include that instance in the page.
Total: 0
0
0
Other components can also affect a ComponentState
by referencing its event handlers or vars
via the .State
attribute.
0