---
title: Children
---

## 普通用法

*大多数情况下，*在组件内部包含有 children 时，您并不关心组件具体有什么类型的 children。在这种情况下，下面的例子就足够了。

```rust
use yew::prelude::*;

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

pub struct List {
    props: ListProps,
}

impl Component for List {
    type Properties = ListProps;
    // ...

    fn view(&self) -> Html {
        html! {
            <div class="list">
                { for self.props.children.iter() }
            </div>
        }
    }
}
```

## 高级用法

当您希望将某一种类型的组件作为 children 传递给您的组件时，您可以使用`yew::html::ChildrenWithProps<T>` 。

```rust
use yew::html::ChildrenWithProps;
use yew::prelude::*;

// ...

#[derive(Properties, Clone)]
pub struct ListProps {
    #[prop_or_default]
    pub children: ChildrenWithProps<Item>,
}

pub struct List {
    props: ListProps,
}

impl Component for ListProps {
    type Properties = ListProps;
    // ...

    fn view(&self) -> Html {
        html! {
            <div class="list">
                { for self.props.children.iter() }
            </div>
        }
    }
}
```

当然，有时您可能需要将 children 限制为几个不同的组件。在这种情况下，您要再深入一点 Yew。

[`derive_more`](https://github.com/JelteF/derive_more) crate 在这种情况下非常有用。如果你不想用它的话, 你需要手动为每个变量实现 `From` 。

```rust
use yew::prelude::*;
use yew::html::ChildrenRenderer;
use yew::virtual_dom::{ VChild, VComp };

// `derive_more::From` implements `From<VChild<Primary>>` and
// `From<VChild<Secondary>>` for `Item` automatically!
#[derive(Clone, derive_more::From)]
pub enum Item {
    Primary(VChild<Primary>),
    Secondary(VChild<Secondary>),
}

// Now, we implment `Into<Html>` so that yew knows how to render `Item`.
impl Into<Html> for Item {
    fn into(self) -> Html {
        match self {
            Self::Primary(child) => child.into(),
            Self::Secondary(child) => child.into(),
        }
    }
}

#[derive(Properties, Clone)]
pub struct ListProps {
    #[prop_or_default]
    pub children: ChildrenRenderer<Item>,
}

pub struct List {
    props: ListProps,
}

impl Component for List {
    type Properties = ListProps;
    // ...

    fn view(&self) -> Html {
        html! {
            <div class="list">
                { for self.props.children.iter() }
            </div>
        }
    }
}
```
