mirror of https://github.com/yewstack/yew
125 lines
3.2 KiB
Plaintext
125 lines
3.2 KiB
Plaintext
---
|
|
title: 'コンポーネント'
|
|
description: 'コンポーネント階層を使用して複雑なレイアウトを作成する'
|
|
---
|
|
|
|
## 基本
|
|
|
|
コンポーネントは `html!` マクロで使用できます:
|
|
|
|
```rust
|
|
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!{
|
|
<>
|
|
// プロパティなし
|
|
<MyComponent />
|
|
|
|
// プロパティを使用
|
|
<MyComponentWithProps user_first_name="Sam" user_last_name="Idle" />
|
|
|
|
// すべてのプロパティを一度に提供
|
|
<MyComponentWithProps ..props.clone() />
|
|
|
|
// 変数のプロパティを使用し、特定の値を上書き
|
|
<MyComponentWithProps user_last_name="Elm" ..props />
|
|
</>
|
|
};
|
|
```
|
|
|
|
## ネスト
|
|
|
|
コンポーネントの `Properties` に `children` フィールドがある場合、子コンポーネント/要素を受け入れることができます。
|
|
|
|
```rust title="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 の[関数的更新構文](https://doc.rust-lang.org/stable/reference/expressions/struct-expr.html#functional-update-syntax)に似ています。
|
|
この基本式は、個別のプロパティを渡した後に現れる必要があります。
|
|
`children` フィールドを持つ基本 props 式を渡す場合、`html!` マクロ内で渡された子要素は、props 内に既に存在する子要素を上書きします。
|
|
|
|
```rust
|
|
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 を上書きします
|
|
<span>{ "I am a child, as you can see" }</span>
|
|
</Container>
|
|
};
|
|
```
|
|
|
|
## 参考例
|
|
|
|
- [関数型 Todo MVC](https://github.com/yewstack/yew/tree/master/examples/function_todomvc)
|
|
- [関数型ルーティング](https://github.com/yewstack/yew/tree/master/examples/function_router)
|