元素
DOM 節點
在 Yew 中手動建立或管理 DOM 節點的原因有很多,例如,在整合可能會導致受控元件衝突的 JS 函式庫時。
透過使用 web-sys
,你可以建立 DOM 元素,並將它們轉換為 Node
(然後可以使用 VRef
將其用為 Html
值)
use web_sys::{Element, Node};
use yew::prelude::*;
use gloo::utils::document;
#[function_component]
fn MyComponent() -> Html {
// memoize as this only needs to be executed once
let node = use_memo(
(),
|_| {
// Create a div element from the document
let div: Element = document().create_element("div").unwrap();
// Add content, classes etc.
div.set_inner_html("Hello, World!");
// Convert Element into a Node
let node: Node = div.into();
// Return that Node as a Html value
Html::VRef(node)
},
);
// use_memo return Rc so we need to deref and clone
(*node).clone()
}
動態標籤名稱
在建置高階元件時,可能會遇到元素的標籤名稱並非靜態的情況。例如,你可能有 Title
元件,它可以視等級屬性而繪畫從 h1
到 h6
的任何內容。Yew 允許你使用 @{name}
動態設定標籤名稱,其中 name
可以是任何傳回字串的表達式,而非使用大型比對表達式。
use yew::prelude::*;
let level = 5;
let text = "Hello World!".to_owned();
html! {
<@{format!("h{}", level)} class="title">{ text }</@>
};
布林屬性
某些內容屬性(例如已選取、隱藏、必要)稱為布林屬性。在 Yew 中,布林屬性需要設定為布林值
use yew::prelude::*;
html! {
<div hidden=true>
{ "This div is hidden." }
</div>
};
這將會產生與下列內容在功能上等效的HTML
<div hidden>This div is hidden.</div>
將布林屬性設定為 false 等同於完全不使用該屬性;可以利用布林表達式的值
use yew::prelude::*;
let no = 1 + 1 != 2;
html! {
<div hidden={no}>
{ "This div is NOT hidden." }
</div>
};
這將會產生下列HTML
<div>This div is NOT hidden.</div>
字串型屬性
除了少數布林屬性之外,您可能還會處理許多字串型 HTML 屬性,而且 Yew 有幾個選項可以將字串型值傳遞至元件。
use yew::{html, virtual_dom::AttrValue};
let str_placeholder = "I'm a str!";
let string_placeholder = String::from("I'm a String!");
let attrvalue_placeholder = AttrValue::from("I'm an AttrValue!");
html! {
<div>
<input placeholder={str_placeholder} />
<input placeholder={string_placeholder} />
<input placeholder={attrvalue_placeholder} />
</div>
};
它們全都有效但我們建議您優先使用 Yew 的自訂 AttrValue
,特別是如果您需要複製它們或將它們作為屬性傳遞至其他元件。
用於 HTML 元素的選用屬性
大多數 HTML 屬性可以使用選用值(Some(x) 或 None)。如果將屬性標記為選用,則讓我們可以省略該屬性。
use yew::prelude::*;
let maybe_id = Some("foobar");
html! {
<div id={maybe_id}></div>
};
如果屬性設定為 None
,屬性將不會設定在 DOM 中。