Children

普通用法

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

  1. use yew::prelude::*;
  2. #[derive(Properties, Clone)]
  3. pub struct ListProps {
  4. #[prop_or_default]
  5. pub children: Children,
  6. }
  7. pub struct List {
  8. props: ListProps,
  9. }
  10. impl Component for List {
  11. type Properties = ListProps;
  12. // ...
  13. fn view(&self) -> Html {
  14. html! {
  15. <div class="list">
  16. { for self.props.children.iter() }
  17. </div>
  18. }
  19. }
  20. }

高级用法

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

  1. use yew::html::ChildrenWithProps;
  2. use yew::prelude::*;
  3. // ...
  4. #[derive(Properties, Clone)]
  5. pub struct ListProps {
  6. #[prop_or_default]
  7. pub children: ChildrenWithProps<Item>,
  8. }
  9. pub struct List {
  10. props: ListProps,
  11. }
  12. impl Component for ListProps {
  13. type Properties = ListProps;
  14. // ...
  15. fn view(&self) -> Html {
  16. html! {
  17. <div class="list">
  18. { for self.props.children.iter() }
  19. </div>
  20. }
  21. }
  22. }

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

derive_more crate 在这种情况下非常有用。如果你不想用它的话, 你需要手动为每个变量实现 From

  1. use yew::prelude::*;
  2. use yew::html::ChildrenRenderer;
  3. use yew::virtual_dom::{ VChild, VComp };
  4. // `derive_more::From` implements `From<VChild<Primary>>` and
  5. // `From<VChild<Secondary>>` for `Item` automatically!
  6. #[derive(Clone, derive_more::From)]
  7. pub enum Item {
  8. Primary(VChild<Primary>),
  9. Secondary(VChild<Secondary>),
  10. }
  11. // Now, we implment `Into<Html>` so that yew knows how to render `Item`.
  12. impl Into<Html> for Item {
  13. fn into(self) -> Html {
  14. match self {
  15. Self::Primary(child) => child.into(),
  16. Self::Secondary(child) => child.into(),
  17. }
  18. }
  19. }
  20. #[derive(Properties, Clone)]
  21. pub struct ListProps {
  22. #[prop_or_default]
  23. pub children: ChildrenRenderer<Item>,
  24. }
  25. pub struct List {
  26. props: ListProps,
  27. }
  28. impl Component for List {
  29. type Properties = ListProps;
  30. // ...
  31. fn view(&self) -> Html {
  32. html! {
  33. <div class="list">
  34. { for self.props.children.iter() }
  35. </div>
  36. }
  37. }
  38. }