1
0

component_props_options.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. 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. 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. cx.render(rsx!(h1 { "{cx.props.number}" }))
  85. }
  86. // ANCHOR_END: DefaultComponent
  87. // ANCHOR: IntoComponent
  88. #[derive(PartialEq, Props)]
  89. struct IntoProps {
  90. #[props(into)]
  91. string: String,
  92. }
  93. fn IntoComponent(cx: Scope<IntoProps>) -> Element {
  94. cx.render(rsx!(h1 { "{cx.props.string}" }))
  95. }
  96. // ANCHOR_END: IntoComponent