component_props_options.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #![allow(non_snake_case)]
  2. use dioxus::prelude::*;
  3. fn main() {
  4. dioxus::desktop::launch(App);
  5. }
  6. fn App(cx: Scope) -> Element {
  7. cx.render(rsx! {
  8. // ANCHOR: OptionalProps_usage
  9. Title {
  10. title: "Some Title",
  11. },
  12. Title {
  13. title: "Some Title",
  14. subtitle: "Some Subtitle",
  15. },
  16. // Providing an Option explicitly won't compile though:
  17. // Title {
  18. // title: "Some Title",
  19. // subtitle: None,
  20. // },
  21. // ANCHOR_END: OptionalProps_usage
  22. // ANCHOR: ExplicitOption_usage
  23. ExplicitOption {
  24. title: "Some Title",
  25. subtitle: None,
  26. },
  27. ExplicitOption {
  28. title: "Some Title",
  29. subtitle: Some("Some Title"),
  30. },
  31. // This won't compile:
  32. // ExplicitOption {
  33. // title: "Some Title",
  34. // },
  35. // ANCHOR_END: ExplicitOption_usage
  36. // ANCHOR: DefaultComponent_usage
  37. DefaultComponent {
  38. number: 5,
  39. },
  40. DefaultComponent {},
  41. // ANCHOR_END: DefaultComponent_usage
  42. // ANCHOR: IntoComponent_usage
  43. IntoComponent {
  44. string: "some &str",
  45. },
  46. // ANCHOR_END: IntoComponent_usage
  47. })
  48. }
  49. // ANCHOR: OptionalProps
  50. #[derive(Props)]
  51. struct OptionalProps<'a> {
  52. title: &'a str,
  53. subtitle: Option<&'a str>,
  54. }
  55. fn Title<'a>(cx: Scope<'a, OptionalProps>) -> Element<'a> {
  56. return cx.render(rsx!(h1{
  57. "{cx.props.title}: ",
  58. [cx.props.subtitle.unwrap_or("No subtitle provided")],
  59. }));
  60. }
  61. // ANCHOR_END: OptionalProps
  62. // ANCHOR: ExplicitOption
  63. #[derive(Props)]
  64. struct ExplicitOptionProps<'a> {
  65. title: &'a str,
  66. #[props(!optional)]
  67. subtitle: Option<&'a str>,
  68. }
  69. fn ExplicitOption<'a>(cx: Scope<'a, ExplicitOptionProps>) -> Element<'a> {
  70. return cx.render(rsx!(h1{
  71. "{cx.props.title}: ",
  72. [cx.props.subtitle.unwrap_or("No subtitle provided")],
  73. }));
  74. }
  75. // ANCHOR_END: ExplicitOption
  76. // ANCHOR: DefaultComponent
  77. #[derive(PartialEq, Props)]
  78. struct DefaultProps {
  79. // default to 42 when not provided
  80. #[props(default = 42)]
  81. number: i64,
  82. }
  83. fn DefaultComponent(cx: Scope<DefaultProps>) -> Element {
  84. return cx.render(rsx!(h1{
  85. "{cx.props.number}",
  86. }));
  87. }
  88. // ANCHOR_END: DefaultComponent
  89. // ANCHOR: IntoComponent
  90. #[derive(PartialEq, Props)]
  91. struct IntoProps {
  92. #[props(into)]
  93. string: String,
  94. }
  95. fn IntoComponent(cx: Scope<IntoProps>) -> Element {
  96. return cx.render(rsx!(h1{
  97. "{cx.props.string}",
  98. }));
  99. }
  100. // ANCHOR_END: IntoComponent