fc_macro.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. use dioxus::prelude::*;
  2. use dioxus_ssr::TextRenderer;
  3. // todo @Jon, support components in the html! macro
  4. // let renderer = TextRenderer::new(|_| html! {<Example name="world"/>});
  5. fn main() {
  6. let renderer = TextRenderer::<()>::new(|_| html! {<div> "Hello world" </div>});
  7. let output = renderer.render();
  8. }
  9. /// An example component that demonstrates how to use the functional_component macro
  10. /// This macro makes writing functional components elegant, similar to how Rocket parses URIs.
  11. ///
  12. /// You don't actually *need* this macro to be productive, but it makes life easier, and components cleaner.
  13. /// This approach also integrates well with tools like Rust-Analyzer.
  14. ///
  15. /// Notice that Context is normally generic over props, but RA doesn't care when in proc-macro mode.
  16. /// Also notice that ctx.props still works like you would expect, so migrating to the macro is easy.
  17. #[fc]
  18. fn example(ctx: &Context, name: String) -> VNode {
  19. html! { <div> "Hello, {name}!" </div> }
  20. }
  21. /*
  22. TODO
  23. /// The macro can also be applied to statics in order to make components less verbose
  24. /// The FC type automatically adds the inference, and property fields are automatically added as function arguments
  25. #[fc]
  26. static Example: FC = |ctx, name: String| {
  27. html! { <div> "Hello, {name}!" </div> }
  28. };
  29. */
  30. // This trait is not exposed to users directly, though they could manually implement this for struct-style components
  31. trait Comp {
  32. type Props: Properties;
  33. fn render(&self, ctx: &mut Context<Self::Props>) -> VNode;
  34. fn builder(&self) -> Self::Props;
  35. }
  36. trait Properties {
  37. fn new() -> Self;
  38. }
  39. impl<T: Properties> Comp for FC<T> {
  40. type Props = T;
  41. fn render(&self, ctx: &mut Context<T>) -> VNode {
  42. let g = self(ctx);
  43. g
  44. }
  45. fn builder(&self) -> T {
  46. T::new()
  47. }
  48. }
  49. #[allow(unused, non_upper_case_globals)]
  50. static MyComp: FC<()> = |ctx| {
  51. html! {
  52. <div>
  53. <p> "hello world" </p>
  54. </div>
  55. }
  56. };
  57. fn my_comp(ctx: &Context<()>) -> VNode {
  58. todo!()
  59. }
  60. fn test() {
  61. let mut ctx = Context { props: &() };
  62. let f = MyComp.render(&mut ctx);
  63. let props = MyComp.builder();
  64. }