メインコンテンツまでスキップ
Version: Next

Components

基本

Componentを実装しているあらゆる型はhtml!マクロの中で使えます:

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

// With Properties
<MyComponent prop1="lorem" prop2="ipsum" />

// With the whole set of props provided at once
<MyComponent ..props />

// With Properties from a variable and specific values overridden
<MyComponent prop2="lorem" ..props />
</>
}

ネスト

childrenフィールドがPropertiesの中にある場合はコンポーネントは子に渡されます。

parent.rs
html! {
<Container>
<h4>{ "Hi" }</h4>
<div>{ "Hello" }</div>
</Container>
}
container.rs
pub struct Container(Props);

#[derive(Properties, Clone)]
pub struct Props {
pub children: Children,
}

impl Component for Container {
type Properties = Props;

// ...

fn view(&self) -> Html {
html! {
<div id="container">
{ self.0.children.clone() }
</div>
}
}
}
note

Propertiesを継承した型はCloneを実装していなければいけません。 これは#[derive(Properties, Clone)]を使うか手でCloneを実装すれば良いです。

Props とネストした子コンポーネント

ネストしたコンポーネントのプロパティは格納しているコンポーネントの型が子である場合はアクセス可能、または変更可能です。 以下の例ではListコンポーネントはListItemコンポーネントをラップできています。 実際の使用においてこのパターンの例についてはyew-routerのソースコードを確認してみてください。 より進んだ例としては Yew のメインのリポジトリにあるnested-listを確認してみてください。

parent.rs
html! {
<List>
<ListItem value="a" />
<ListItem value="b" />
<ListItem value="c" />
</List>
}
list.rs
pub struct List(Props);

#[derive(Properties, Clone)]
pub struct Props {
pub children: ChildrenWithProps<ListItem>,
}

impl Component for List {
type Properties = Props;

// ...

fn view(&self) -> Html {
html!{{
for self.0.children.iter().map(|mut item| {
item.props.value = format!("item-{}", item.props.value);
item
})
}}
}
}