跳至主要內容
版本: 0.21

特性

特性使子元件和父元件可以彼此通訊。每個元件都有關聯的特性類型,說明從父元件傳遞的內容。理論上,這可以是任何實作 Properties 設定檔的類型,但實際上,除了作為每個欄位代表一個特性的結構外,沒有理由讓它成為任何其他類型。

衍生巨集

而不是自己實作 Properties 設定檔,您應該使用 #[derive(Properties)],以自動產生實作。您使用 Properties 衍生的類型也必須實作 PartialEq

欄位屬性

當衍生 Properties 時,預設所有欄位都必填。以下屬性可以讓您給予您的 prop 初始值,它們將用於這些 prop 未設定為其他值的狀況。

提示

屬性在 Rustdoc 生成的文件中不可見。您屬性的文件字串應說明屬性是否為選擇性的,以及是否有特殊預設值。

#[prop_or_default]

使用 Default 特徵初始化屬性值,並採用欄位型別的預設值。

#[prop_or(value)]

使用 value 來初始化屬性值。value 可以是任何傳回欄位型別的表達式。例如,若要將布林屬性預設為 true,請使用屬性 #[prop_or(true)]

#[prop_or_else(function)]

呼叫 function 來初始化屬性值。function 應具備 FnMut() -> T 函數標記,其中 T 是欄位型別。

PartialEq

Properties 要求實作 PartialEq。這是為了讓 Yew 可以藉由比較來呼叫 changed 方法,僅在它們變更時才會呼叫。

使用 Properties 時的記憶體/速度消耗

在內部,屬性是經過參考計數的。這表示只有指標會傳遞給元件樹以取得屬性。這讓我們的成本降低,不用複製整個屬性,因為那可能很昂貴。

提示

利用 AttrValue,此為我們自訂的屬性值型別,而不是將它們定義為字串或其他類似型別。

範例

use yew::Properties;
/// Importing the AttrValue from virtual_dom
use yew::virtual_dom::AttrValue;

#[derive(Clone, PartialEq)]
pub enum LinkColor {
Blue,
Red,
Green,
Black,
Purple,
}

fn create_default_link_color() -> LinkColor {
LinkColor::Blue
}

#[derive(Properties, PartialEq)]
pub struct LinkProps {
/// The link must have a target.
href: AttrValue,
/// Also notice that we are using AttrValue instead of String
text: AttrValue,
/// Color of the link. Defaults to `Blue`.
#[prop_or_else(create_default_link_color)]
color: LinkColor,
/// The view function will not specify a size if this is None.
#[prop_or_default]
size: Option<u32>,
/// When the view function does not specify active, it defaults to true.
#[prop_or(true)]
active: bool,
}

屬性巨集

yew::props! 巨集讓您可以建立屬性,方式與 html! 巨集相同。

此巨集使用與結構表達式相同的語法,但您無法使用屬性或基本表達式 (Foo { ..base })。型別路徑可以指向屬性 (path::to::Props) 或元件的關聯屬性 (MyComp::Properties) )。

use yew::{props, Properties, virtual_dom::AttrValue};

#[derive(Clone, PartialEq)]
pub enum LinkColor {
Blue,
Red,
Green,
Black,
Purple,
}

fn create_default_link_color() -> LinkColor {
LinkColor::Blue
}

#[derive(Properties, PartialEq)]
pub struct LinkProps {
/// The link must have a target.
href: AttrValue,
/// Also notice that we're using AttrValue instead of String
text: AttrValue,
/// Color of the link. Defaults to `Blue`.
#[prop_or_else(create_default_link_color)]
color: LinkColor,
/// The view function will not specify a size if this is None.
#[prop_or_default]
size: Option<u32>,
/// When the view function doesn't specify active, it defaults to true.
#[prop_or(true)]
active: bool,
}

impl LinkProps {
/// Notice that this function receives href and text as String
/// We can use `AttrValue::from` to convert it to a `AttrValue`
pub fn new_link_with_size(href: String, text: String, size: u32) -> Self {
props! {LinkProps {
href: AttrValue::from(href),
text: AttrValue::from(text),
size,
}}
}
}