mirror of
https://github.com/yewstack/yew.git
synced 2025-12-08 21:26:25 +00:00
* Add doc-test to test website code snippets Heavily inspired by tokio-rs/website repo. * Fix code snippets to pass doc tests Some code snippets are explicitly ignored and some are not run to avoid having to include dependencies for one liners. * Add website code snippet tests to CI * Fix CI * Remove doc-test from workspace * Exclude doc-test from workspace * Refactor code snippets and tests Code snippets can import types from doc_test crate i.e.: ```rust use doc_test::agents::EventBus; ``` This allows for moving some boilerplate away from the example and still checks that the code compiles correctly. Also some slight changes to some of the examples and the information about `ComponentLink` which is deprecated. * Move doc-test to packages * Rename doc-test crate to website-test The new name makes it more clear the purpose of this crate. * fix ci
1.4 KiB
1.4 KiB
| title | description |
|---|---|
| Refs | Out-of-band DOM access |
The ref keyword can be used inside of any HTML element or component to get the DOM Element that
the item is attached to. This can be used to make changes to the DOM outside of the view lifecycle
method.
This is useful for getting ahold of canvas elements, or scrolling to different sections of a page.
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.
The syntax is:
use yew::{html, web_sys::Element, Component, Context, Html, NodeRef};
struct Comp {
node_ref: NodeRef,
}
impl Component for Comp {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
// highlight-next-line
node_ref: NodeRef::default(),
}
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
// highlight-next-line
<div ref={self.node_ref.clone()}></div>
}
}
fn rendered(&mut self, _ctx: &Context<Self>, _first_render: bool) {
// highlight-start
let has_attributes = self.node_ref
.cast::<Element>()
.unwrap()
.has_attributes();
// highlight-end
}
}