メインコンテンツへ移動
バージョン: 0.21

コールバック

コールバックは、イベント処理中にコンポーネントツリーを上向きに非同期で通信したり、エージェントまたは DOM などの他のものと通信するために使用します。内部的に、その型は Rc でラップされた Fn のみで、それらを安価にクローンできるようにします。

手動で呼び出す場合は、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"

コールバックを props として渡す

yew の一般的なパターンは、コールバックを作成して prop として渡すことです。

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>
}
}