Rust中Stylist无法将&str隐式转换为StyleSource问题求助
解决Stylist中
From<&str>未实现StyleSource的报错 问题原因
Stylist新版本(如v0.14+)调整了API,Style::new不再直接接受&str参数,而是要求传入实现Into<StyleSource>的类型,旧教程的写法已不适用。
解决方案
方案1:使用css!宏(推荐)
css!宏会将CSS字符串转换为合法的StyleSource,还能在编译阶段检查CSS语法:
use stylist::{yew::styled_component, Style, css}; #[styled_component(App)] pub fn app() -> Html { let stylesheet = Style::new(css!("background-color: red;")).unwrap(); html! { <div class={stylesheet}> <h1>{"Hello World using stylesheet!"}</h1> <p>{"some more text..."}</p> </div> } }
方案2:显式转换为StyleSource::Inline
如果需要使用字符串变量,可以手动将&str转换为StyleSource:
use stylist::{yew::styled_component, Style, StyleSource}; #[styled_component(App)] pub fn app() -> Html { let style_str = "background-color: red;"; let stylesheet = Style::new(StyleSource::Inline(style_str.into())).unwrap(); html! { <div class={stylesheet}> <h1>{"Hello World using stylesheet!"}</h1> <p>{"some more text..."}</p> </div> } }
内容的提问来源于stack exchange,提问作者xD-prateek
相关产品推荐
相关产品推荐

