跳至主要内容
版本: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>
};

相关示例