Skip to content

Yew

使用 rust 编译的 wasm 构建网页前端。

使用 trunk 构建

index.html 作为 config 文件。不必添加 cdylib 作为库目标,直接将 main 函数作为入口。

trunk serve
trunk build --release

结合 JS 项目

web-sys 提供网页 API 的绑定。

组件

组件可以被渲染为 DOM

组件的生命周期

  • create
  • view
  • rendered
  • update

function_component

简化版本的组件

#[function_component(HelloWorld)]
fn hello_world() -> Html {
    html! { "Hello world" }
}

props

传递 props 给组件

#[derive(Properties, PartialEq)]
pub struct Props {
    pub is_loading: bool,
}

#[function_component]
fn HelloWorld(props: &Props) -> Html {
    html! {<>{props.is_loading.clone()}</>}
}

#[function_component]
fn App() -> Html {
    html! {<HelloWorld is_loading={true} />}
}

state

用于管理 function component 中的状态

let counter = use_state(|| 0);
let onclick = {
    let counter = counter.clone();
    Callback::from(move |_| counter.set(*counter + 1))
};

ref

在状态改变的时候不会被通知

use_effect

use_effect(move || {
    // Make a call to DOM API after component is rendered
    gloo_utils::document().set_title(&format!("You clicked {} times", *counter_one));
    // Perform the cleanup
    || gloo_utils::document().set_title(&format!("You clicked 0 times"))
});

use_effect_with_deps

在传递的参数 deps 改变时调用 callback

contexts

使用 contexts 避免 props drilling

//inside App
let theme = use_memo(|_| Theme {
    foreground: "yellow".to_owned(),
    background: "pink".to_owned(),
}, ());
html! {
    <ContextProvider<Rc<Theme>> context={theme}>
        <NavButton />
    </ContextProvider<Rc<Theme>>>
}

//inside NavButton
let theme = use_context::<Theme>();
html! {
    //use theme
}

router