component_props_options.rs 2.3 KB

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