如何在Yew 项目中使用css 文件

571 阅读1分钟
  1. Cargo.toml 添加 stylist 依赖: github.com/futursolo/s…

     stylist = {version = "0.10", features = ["yew"]}
    
  2. 创建 app.css 文件

  3. app.rs 中导入 app.css 并添加样式。注意使用的是 include_str! 宏。

     const STYLE_FILE: &str = include_str!("./app.css");
    
  4. 通过 stylist 创建 style

    • let style = Style::new(style_str).expect("Failed to create style");
  5. 使用 style

  6. css 参考代码:

    * {
      font-size: 1rem;
    }
    
    h1 {
      font-size: 2rem;
    }
    
    .my_title {
      color: darkmagenta;
    }
    
    ul {
      padding-left: 0;
    }
    
    ul li {
      font-size: 1rem;
      list-style: none;
      color: green;
      height: 1.5rem;
    }
    
  7. yew 参考代码

    use stylist::{yew::styled_component, Style};
    use yew::prelude::*;
    
    const STYLE_FILE: &str = include_str!("./app.css");
    
    #[styled_component(App)]
    pub fn app() -> Html {
        let class = "my_title";
        let tasks = vec!["learn Rust", "learn Yew", "learn React"];
        let style = Style::new(STYLE_FILE).expect("Failed to create style");
    
        html! {
            <div class={style}>
                <h1 class={class}>{"Hello, world!"}</h1>
                <ul>
                    {render_list(&tasks)}
                </ul>
            </div>
        }
    }
    
    fn render_list(list: &Vec<&str>) -> Html {
        list.iter()
            .map(|&item| html!(<li key={item} >{item}</li>))
            .collect()
    }
    
    
  8. 浏览器效果

    image.png