组件
基础
任何实现了 Component trait 的类型都可被用在 html! 宏中:
1. html!{
2. <>
3. // 没有属性
4. <MyComponent />
6. // 具有属性
7. <MyComponent prop1="lorem" prop2="ipsum" />
9. // 同时提供全套的 props
10. <MyComponent ..props />
11. </>
12. }
嵌套
如果组件的 Properties 中有 children 字段,则可以被传递子组件。
{% code title=”parent.rs” %}
1. html! {
2. <Container>
3. <h4>{ "Hi" }</h4>
4. <div>{ "Hello" }</div>
5. </Container>
6. }
{% endcode %}
{% code title=”container.rs” %}
1. pub struct Container(Props);
3. #[derive(Properties)]
4. pub struct Props {
5. pub children: Children,
6. }
8. impl Component for Container {
9. type Properties = Props;
11. // ...
13. fn view(&self) -> Html {
14. html! {
15. <div id="container">
16. { self.0.children.clone() }
17. </div>
18. }
19. }
20. }
{% endcode %}
拥有 Props 的嵌套子组件
如果包含组件标注了 children 的类型,则可以访问和更改嵌套组件的属性。在下面的示例中,List 组件可以包含 ListItem 组件。有关此模式的真实示例,请查看 yew-router 的源码。有关更高级的示例,请在 yew 主仓库中查看 nested-list 示例代码。
{% code title=”parent.rs” %}
1. html! {
2. <List>
3. <ListItem value="a" />
4. <ListItem value="b" />
5. <ListItem value="c" />
6. </List>
7. }
{% endcode %}
{% code title=”list.rs” %}
1. pub struct List(Props);
3. #[derive(Properties)]
4. pub struct Props {
5. pub children: ChildrenWithProps<ListItem>,
6. }
8. impl Component for List {
9. type Properties = Props;
11. // ...
13. fn view(&self) -> Html {
14. html!{{
15. for self.0.children.iter().map(|mut item| {
16. item.props.value = format!("item-{}", item.props.value);
17. item
18. })
19. }}
20. }
21. }
{% endcode %}
