Components

Basic

Any type that implements Component can be used in the html! macro:

  1. html!{
  2. <>
  3. // No properties
  4. <MyComponent />
  5. // With Properties
  6. <MyComponent prop1="lorem" prop2="ipsum" />
  7. // With the whole set of props provided at once
  8. <MyComponent with props />
  9. </>
  10. }

Nested

Components can be passed children if they have a children field in their Properties.

  1. html! {
  2. <Container>
  3. <h4>{ "Hi" }</h4>
  4. <div>{ "Hello" }</div>
  5. </Container>
  6. }
  1. pub struct Container(Props);
  2. #[derive(Properties, Clone)]
  3. pub struct Props {
  4. pub children: Children,
  5. }
  6. impl Component for Container {
  7. type Properties = Props;
  8. // ...
  9. fn view(&self) -> Html {
  10. html! {
  11. <div id="container">
  12. { self.0.children.clone() }
  13. </div>
  14. }
  15. }
  16. }

Components - 图1

note

Types for which you derive Properties must also implement Clone. This can be done by either using #[derive(Properties, Clone)] or manually implementing Clone for your type.

Nested Children with Props

Nested component properties can be accessed and mutated if the containing component types its children. In the following example, the List component can wrap ListItem components. For a real world example of this pattern, check out the yew-router source code. For a more advanced example, check out the nested-list example in the main yew repository.

  1. html! {
  2. <List>
  3. <ListItem value="a" />
  4. <ListItem value="b" />
  5. <ListItem value="c" />
  6. </List>
  7. }
  1. pub struct List(Props);
  2. #[derive(Properties, Clone)]
  3. pub struct Props {
  4. pub children: ChildrenWithProps<ListItem>,
  5. }
  6. impl Component for List {
  7. type Properties = Props;
  8. // ...
  9. fn view(&self) -> Html {
  10. html!{{
  11. for self.0.children.iter().map(|mut item| {
  12. item.props.value = format!("item-{}", item.props.value);
  13. item
  14. })
  15. }}
  16. }
  17. }