跳至主要內容
版本:0.21

組件

基本

組件可以使用在 html! 巨集中

use yew::prelude::*;

#[function_component]
fn MyComponent() -> Html {
html! {
{ "This component has no properties!" }
}
}

#[derive(Clone, PartialEq, Properties)]
struct Props {
user_first_name: String,
user_last_name: String,
}

#[function_component]
fn MyComponentWithProps(props: &Props) -> Html {
let Props { user_first_name, user_last_name } = props;
html! {
<>{"user_first_name: "}{user_first_name}{" and user_last_name: "}{user_last_name}</>
}
}

let props = Props {
user_first_name: "Bob".to_owned(),
user_last_name: "Smith".to_owned(),
};

html!{
<>
// No properties
<MyComponent />

// With Properties
<MyComponentWithProps user_first_name="Sam" user_last_name="Idle" />

// With the whole set of props provided at once
<MyComponentWithProps ..props.clone() />

// With Properties from a variable and specific values overridden
<MyComponentWithProps user_last_name="Elm" ..props />
</>
};

嵌套

如果組件有 Properties 中有 children 欄位,組件可以接受子組件/元素

parent.rs
use yew::prelude::*;

#[derive(PartialEq, Properties)]
struct Props {
id: String,
children: Html,
}

#[function_component]
fn Container(props: &Props) -> Html {
html! {
<div id={props.id.clone()}>
{ props.children.clone() }
</div>
}
}

html! {
<Container id="container">
<h4>{ "Hi" }</h4>
<div>{ "Hello" }</div>
</Container>
};

html! 巨集允許您傳遞一個基本表達式,語法為 ..props,而非逐一指定各個屬性,類似於 Rust 的 函數更新語法。這個基本表達式必須在傳遞各個單獨屬性之後寫入。當傳遞帶有 children 欄位的基本屬性表達式時, html! 巨集中傳遞的子元素會覆寫屬性中已有的子元素。

use yew::prelude::*;

#[derive(PartialEq, Properties)]
struct Props {
id: String,
children: Html,
}

#[function_component]
fn Container(props: &Props) -> Html {
html! {
<div id={props.id.clone()}>
{ props.children.clone() }
</div>
}
}

let props = yew::props!(Props {
id: "container-2",
children: Html::default(),
});

html! {
<Container ..props>
// props.children will be overwritten with this
<span>{ "I am a child, as you can see" }</span>
</Container>
};

相關範例