コンポーネント
基本
コンポーネントは`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!`マクロでは、各プロパティを個別に指定する代わりに、Rustの関数型更新構文と同様に、`..props`構文で基本式を渡すことができます。この基本式は、個々のプロパティを渡した後に記述する必要があります。`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>
};