pub trait Component: Sized + 'static {
// Required method
fn render(&self) -> VNode;
// Provided methods
fn key(self, key: Option<impl KeyType>) -> Keyed<Self> { ... }
fn build(self) -> VNode { ... }
fn memoized(self) -> Memoized<Self>
where Self: PartialEq { ... }
}
Expand description
Implement this trait on a struct to create a component with the struct as props.
The props will be completely controlled by Rust, which makes rendering them
relatively simple in Rust. However, since the props struct cannot be
constructed in JS, these components cannot be exposed to JS. This means only
components written in Rust can render a Component
by default.
See export_components!
for how to expose
components for JS consumption.
§Example
struct Counter(i32);
impl Component for Counter {
fn render(&self) -> VNode {
h!(div).build(("Counter: ", self.0))
}
}
Required Methods§
Sourcefn render(&self) -> VNode
fn render(&self) -> VNode
The render function.
Do not call this method in another render function. Instead, use
Component::build()
to include your component.
Provided Methods§
Sourcefn memoized(self) -> Memoized<Self>where
Self: PartialEq,
fn memoized(self) -> Memoized<Self>where
Self: PartialEq,
Returns a memoized version of your component that skips rendering if props haven’t changed.
If your component renders the same result given the same props, you can memoize your component for a performance boost.
You have to implement PartialEq
on your Component
for this to work.
§Example
#[derive(PartialEq)]
struct MessageBox {
message: Rc<str>,
}
impl Component for MessageBox {
fn render(&self) -> VNode {
h!(h1[."message-box"]).build(&*self.message)
}
}
struct App;
impl Component for App {
fn render(&self) -> VNode {
h!(div[#"app"]).build(
MessageBox {
message: Rc::from("Hello World!"),
}
.memoized()
.build()
)
}
}
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.