Refs
ref
は、任意の HTML 要素やコンポーネントの内部で、割り当てられている DOMElement
を取得するために使用することができます。
これは、view
ライフサイクルメソッドの外で DOM に変更を加えるために使用できます。
これは、キャンバスの要素を取得したり、ページの異なるセクションにスクロールしたりするのに便利です。
For example, using a NodeRef
in a component's rendered
method allows you to make draw calls to
a canvas element after it has been rendered from view
.
構文は以下の通りです:
use web_sys::Element;
use yew::{html, Component, Context, Html, NodeRef};
struct Comp {
node_ref: NodeRef,
}
impl Component for Comp {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
node_ref: NodeRef::default(),
}
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<div ref={self.node_ref.clone()}></div>
}
}
fn rendered(&mut self, _ctx: &Context<Self>, _first_render: bool) {
let has_attributes = self.node_ref
.cast::<Element>()
.unwrap()
.has_attributes();
}
}