maomi
介绍
入门
文档

属性

使用组件属性

组件可以包含若干能够在模板上被赋值的字段。

属性需要被 Prop 包裹。 Prop 类型实现有 Deref ,它可以被解引用到它内含的类型。

#[component(Backend = DomBackend)]
struct MyChild {
template: template! {
<div> { format!("The content is {}", *self.content) } </div>
},
pub content: Prop<String>,
}
impl Component for MyChild {
fn new() -> Self {
Self {
template: Default::default(),
content: Prop::new("default".to_string()),
}
}
}
#[component(Backend = DomBackend)]
struct MyWebsite {
template: template! {
<MyChild content="from MyWebsite" />
}
}
impl Component for MyWebsite {
fn new() -> Self {
Self {
template: Default::default(),
}
}
}

注意属性字段需要 pub 来使得其他 rust 模块的模板可以访问到它。

双向属性

普通的属性是单向的:组件从组件的使用者处收到数据。

有时希望它是双向的,例如需要将 input 值传递给使用者的时候。

这种情况时,可以使用 BindingProp 和 BindingValue 。但双向数据更新并不会自动触发模板更新。如果需要更新模板,就需要手工生成一个 task 来更新。

use maomi::prop::{BindingProp, BindingValue};
use maomi_dom::event::*;
#[component(Backend = DomBackend)]
struct MyChild {
template: template! {
<input value=&{ self.input_value } input=@value_changed() />
},
input_value: BindingValue<String>,
pub content: BindingProp<String>,
pub change: Event<()>,
}
impl Component for MyChild {
fn new() -> Self {
Self {
template: Default::default(),
input_value: Default::default(),
content: Default::default(),
change: Default::default(),
}
}
}
impl MyChild {
fn value_changed(this: ComponentEvent<Self, InputEvent>) {
this.task_with(|this, _| {
this.content.set(this.input_value.get());
this.change.trigger(&mut ());
});
}
}
#[component(Backend = DomBackend)]
struct MyWebsite {
template: template! {
<MyChild content=&{ self.content } change=@content_changed() />
<div> { self.content.get() } </div>
},
content: BindingValue<String>,
}
impl Component for MyWebsite {
fn new() -> Self {
Self {
template: Default::default(),
content: Default::default(),
}
}
}
impl MyWebsite {
fn content_changed(this: ComponentEvent<Self, ()>) {
this.task(|_| {});
}
}

注意 BindingProp 和 BindingValue 未实现 Deref ,需要用 get 函数来获取其中的值。