回呼函式
回呼函式用於在組件樹中進行非同步通訊,並用於事件處理,如代理或 DOM。內部類型只使用了 Fn
包裝 Rc
讓他們可以輕易地被複製。
如果你想要手動呼叫,它們有一個 emit
函式。
use yew::{html, Component, Context, Html, Callback};
let cb: Callback<String, String> = Callback::from(move |name: String| {
format!("Bye {}", name)
});
let result = cb.emit(String::from("Bob")); // call the callback
// web_sys::console::log_1(&result.into()); // if uncommented will print "Bye Bob"
將回呼函式作為道具傳遞
在 yew 中,產生一個回呼函式並作為道具傳遞是一個常見模式。
use yew::{function_component, html, Html, Properties, Callback};
#[derive(Properties, PartialEq)]
pub struct Props {
pub on_name_entry: Callback<String>,
}
#[function_component]
fn HelloWorld(props: &Props) -> Html {
props.on_name_entry.emit(String::from("Bob"));
html! { "Hello" }
}
// Then supply the prop
#[function_component]
fn App() -> Html {
let on_name_entry: Callback<String> = Callback::from(move |name: String| {
let greeting = format!("Hey, {}!", name);
// web_sys::console::log_1(&greeting.into()); // if uncommented will print
});
html! { <HelloWorld {on_name_entry} /> }
}
DOM 事件和回呼函式
回呼函式也用於鉤住 DOM 事件。
舉例來說,在此我們定義一個回呼函式,將在使用者點擊按鈕時被呼叫
use yew::{function_component, html, Html, Properties, Callback};
#[function_component]
fn App() -> Html {
let onclick = Callback::from(move |_| {
let greeting = String::from("Hi there");
// web_sys::console::log_1(&greeting.into()); // if uncommented will print
});
html! {
<button {onclick}>{ "Click" }</button>
}
}