mirror of
https://github.com/yewstack/yew.git
synced 2025-12-08 21:26:25 +00:00
* Reword to use double-dot syntax instead of "with" * Implement double-dot syntax for props in components * Update documentation with new syntax * Update forgotten doc * Add descriptive comments * Check props and base expression * Make compatible with 1.49.0 by removing then * Fix website tests * Update error output * Implicitly convert string literals to String if they are listed as props * Remove unused keyword * Rename function for checking if string literal * Fix weird formatting * Update code based on review * Update website/docs/concepts/html/components.md Co-authored-by: mc1098 <m.cripps1@uni.brighton.ac.uk> * Base expression span includes dot2 now * Improve specificity of error message * Chain together error messages * Add an example failure case to illustrate combined error message * Update based on review comments * Fix missing clones Co-authored-by: mc1098 <m.cripps1@uni.brighton.ac.uk>
2.5 KiB
2.5 KiB
| title | description |
|---|---|
| Components | Create complex layouts with component hierarchies |
基本
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の中にある場合はコンポーネントは子に渡されます。
html! {
<Container>
<h4>{ "Hi" }</h4>
<div>{ "Hello" }</div>
</Container>
}
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を確認してみてください。
html! {
<List>
<ListItem value="a" />
<ListItem value="b" />
<ListItem value="c" />
</List>
}
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
})
}}
}
}