You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 21:12:49