pub trait Component: Sized {
type Props;
type State;
type Msg: Clone + Send + 'static;
// Required methods
fn init(props: &Self::Props) -> Self::State;
fn update(state: &mut Self::State, msg: Self::Msg) -> Cmd<Self::Msg>;
fn view(
props: &Self::Props,
state: &Self::State,
ctx: &mut ViewCtx<'_, Self::Msg>,
);
}Expand description
A reusable UI component with its own state and messages
Components follow a “parent owns state” model (Elm-style). The parent allocates and stores the component’s State, and passes Props when rendering.
§Example
ⓘ
struct Counter;
impl Component for Counter {
type Props = i32; // initial value
type State = i32; // current count
type Msg = CounterMsg;
fn init(props: &Self::Props) -> Self::State {
*props
}
fn update(state: &mut Self::State, msg: Self::Msg) -> Cmd<Self::Msg> {
match msg {
CounterMsg::Increment => *state += 1,
CounterMsg::Decrement => *state -= 1,
}
Cmd::none()
}
fn view(props: &Self::Props, state: &Self::State, ctx: &mut ViewCtx<Self::Msg>) {
ctx.horizontal(|ctx| {
ctx.button("-", CounterMsg::Decrement);
ctx.ui.label(format!("{}", state));
ctx.button("+", CounterMsg::Increment);
});
}
}Required Associated Types§
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.