範圍
元件的 Scope<_>
API
元件「Scope
」是元件透過訊息建立呼叫回並更新自己的機制。我們透過呼叫傳遞至元件的內容物件上的 link()
來取得這個參照。
send_message
傳送訊息至元件。訊息是由 update
方法處理的,方法會決定元件是否應該重新渲染。
send_message_batch
一次傳送多則訊息至元件。這與 send_message
類似,但若任何訊息造成 update
方法回傳 true
,元件會在處理批次中的所有訊息後重新渲染。
如果已提供向量為空,此函式什麼也不會做。
callback
建立一個在執行時將訊息傳送至該元件的回呼。它會在幕後呼叫 send_message
並傳入由提供的閉包傳回的訊息。
use yew::{html, Component, Context, Html};
enum Msg {
Text(String),
}
struct Comp;
impl Component for Comp {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
// Create a callback that accepts some text and sends it
// to the component as the `Msg::Text` message variant.
let cb = ctx.link().callback(|text: String| Msg::Text(text));
// The previous line is needlessly verbose to make it clearer.
// It can be simplified it to this:
let cb = ctx.link().callback(Msg::Text);
// Will send `Msg::Text("Hello World!")` to the component.
cb.emit("Hello World!".to_owned());
html! {
// html here
}
}
}
batch_callback
建立一個在執行時將批次訊息傳送至該元件的回呼。它與 callback
的差異在於傳遞給此方法的閉包不必傳回訊息。相反地,閉包可以傳回 Vec<Msg>
或 Option<Msg>
,其中 Msg
是元件的訊息類型。
Vec<Msg>
會視為一批次訊息,並在幕後使用 send_message_batch
。
如果 Option<Msg>
是 Some
,便會呼叫 send_message
。如果其值是 None
,則不會執行任何動作。這可用於在視情況而定,不需要更新的狀況之下。
這是透過 SendAsMessage
規範來達成,而此規範僅對此類類型加以實作。你可以為自己的類型實作 SendAsMessage
,這將讓你在 batch_callback
中使用它們。