Elements

标签结构

元素标签必须是自闭合的 <... />,或是每个标签都有一个对应的闭合标签。

Open - Close

Invalid

Self-closing

Invalid

1. html! {  <div id="my_div"></div>}
1. html! {  <div id="my_div"> // <- 缺少闭合标签}
1. html! {  <input id="my_input" />}
1. html! {  <input id="my_input"> // <- 没有自闭合}

Elements - 图1

note

为方便起见,一些 通常 需要闭合标签的元素是被允许自闭合的。例如,html! { <div class="placeholder" /> } 这样写是有效的。

Children

轻松创建复杂的嵌套 HTML 和 SVG 布局:

HTML

SVG

1. html! {    <div>        <div data-key="abc"></div>        <div class="parent">            <span class="child" value="anything"></span>            <label for="first-name">{ "First Name" }</label>            <input type="text" id="first-name" value="placeholder" />            <input type="checkbox" checked=true />            <textarea value="write a story" />            <select name="status">                <option selected=true disabled=false value="">{ "Selected" }</option>                <option selected=false disabled=true value="">{ "Unselected" }</option>            </select>        </div>    </div>}
1. html! {    <svg width="149" height="147" viewBox="0 0 149 147" fill="none" xmlns="http://www.w3.org/2000/svg">        <path d="M60.5776 13.8268L51.8673 42.6431L77.7475 37.331L60.5776 13.8268Z" fill="#DEB819"/>        <path d="M108.361 94.9937L138.708 90.686L115.342 69.8642" stroke="black" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>        <g filter="url(#filter0_d)">            <circle cx="75.3326" cy="73.4918" r="55" fill="#FDD630"/>            <circle cx="75.3326" cy="73.4918" r="52.5" stroke="black" stroke-width="5"/>        </g>        <circle cx="71" cy="99" r="5" fill="white" fill-opacity="0.75" stroke="black" stroke-width="3"/>        <defs>            <filter id="filter0_d" x="16.3326" y="18.4918" width="118" height="118" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">                <feGaussianBlur stdDeviation="2"/>                <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/>            </filter>        </defs>    </svg>}

Classes

有许多方便的选项可用于元素指定 classes:

Literal

Multiple

Interpolated

Expression

Tuple

Vector

1. html! {  <div class="container"></div>}
1. html! {  <div class="container center-align"></div>}
1. html! {  <div class=format!("{}-container", size)></div>}
1. html! {  <div class=self.classes()></div>}
1. html! {  <div class=("class-1", "class-2")></div>}
1. html! {  <div class=vec!["class-1", "class-2"]></div>}

监听器

监听器属性需要传递一个由闭包包裹的 Callback。创建回调的方式取决于你希望你的应用程序如何响应监听器事件:

Component handler

Agent Handler

Other Cases

1. struct MyComponent {    link: ComponentLink<Self>,}enum Msg {    Click,}impl Component for MyComponent {    type Message = Msg;    type Properties = ();    fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {        MyComponent { link }    }    fn update(&mut self, msg: Self::Message) -> ShouldRender {        match msg {            Msg::Click => {                // 处理 Click            }        }    }    fn view(&self) -> Html {        // 从组件 link 中创建回调来在组件中处理它        let click_callback = self.link.callback(|_: ClickEvent| Msg::Click);        html! {            <button onclick=click_callback>                { "Click me!" }            </button>        }    }}
1. struct MyComponent {    worker: Dispatcher<MyWorker>,}impl Component for MyComponent {    type Message = ();    type Properties = ();    fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {        MyComponent {            worker: MyWorker::dispatcher()        }    }    fn update(&mut self, _: Self::Message) -> ShouldRender {        false    }    fn view(&self) -> Html {        // 从 worker 中创建回调来在另一个上下文中处理它        let click_callback = self.worker.callback(|_: ClickEvent| WorkerMsg::Process);        html! {            <button onclick=click_callback>                { "Click me!" }            </button>        }    }}
1. struct MyComponent;impl Component for MyComponent {    type Message = ();    type Properties = ();    fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {        MyComponent    }    fn update(&mut self, _: Self::Message) -> ShouldRender {        false    }    fn view(&self) -> Html {        // 创建一个短暂的回调        let click_callback = Callback::from(|| {            ConsoleService::new().log("clicked!");        });        html! {            <button onclick=click_callback>                { "Click me!" }            </button>        }    }}

事件类型

Elements - 图2

note

在下表中, 只有当yew与web-sys一起使用时,才应使用web-sys的事件类型(默认情况下启用)。如果您使用的是yew-stdweb crate,请使用stdweb。更多有关信息,请参见有关选择是选择web-sys还是stdweb

Elements - 图3

note

下表中提到的所有事件类型都已在yew::events下重新导出。 比起手动将 web-sys或stdweb作为依赖项添加到你的 crate 中, 使用yew::events中的类型更容易确保版本兼容性,因为这样可以避免与指定的 Yew 版本冲突。

事件名称 web_sys 事件类型 stdweb 事件类型
onabort Event ResourceAbortEvent
onauxclick MouseEvent AuxClickEvent
onblur FocusEvent BlurEvent
oncancel Event 不支持
oncanplay Event 不支持
oncanplaythrough Event 不支持
onchange ChangeData ChangeData
onclick MouseEvent ClickEvent
onclose Event 不支持
oncontextmenu MouseEvent ContextMenuEvent
oncuechange Event 不支持
ondblclick MouseEvent DoubleClickEvent
ondrag DragEvent DragEvent
ondragend DragEvent DragEndEvent
ondragenter DragEvent DragEnterEvent
ondragexit DragEvent DragExitEvent
ondragleave DragEvent DragLeaveEvent
ondragover DragEvent DragOverEvent
ondragstart DragEvent DragStartEvent
ondrop DragEvent DragDropEvent
ondurationchange Event 不支持
onemptied Event 不支持
onended Event 不支持
onerror Event ResourceErrorEvent
onfocus FocusEvent FocusEvent
onformdata Event 不支持
oninput InputData InputData
oninvalid Event 不支持
onkeydown KeyboardEvent KeyDownEvent
onkeypress KeyboardEvent KeyPressEvent
onkeyup KeyboardEvent KeyUpEvent
onload Event ResourceLoadEvent
onloadeddata Event 不支持
onloadedmetadata Event 不支持
onloadstart ProgressEvent LoadStartEvent
onmousedown MouseEvent MouseDownEvent
onmouseenter MouseEvent MouseEnterEvent
onmouseleave MouseEvent MouseLeaveEvent
onmousemove MouseEvent MouseMoveEvent
onmouseout MouseEvent MouseOutEvent
onmouseover MouseEvent MouseOverEvent
onmouseup MouseEvent MouseUpEvent
onpause Event 不支持
onplay Event 不支持
onplaying Event 不支持
onprogress ProgressEvent ProgressEvent
onratechange Event 不支持
onreset Event 不支持
onresize Event ResizeEvent
onscroll Event ScrollEvent
onsecuritypolicyviolation Event 不支持
onseeked Event 不支持
onseeking Event 不支持
onselect Event 不支持
onslotchange Event SlotChangeEvent
onstalled Event 不支持
onsubmit FocusEvent SubmitEvent
onsuspend Event 不支持
ontimeupdate Event 不支持
ontoggle Event 不支持
onvolumechange Event 不支持
onwaiting Event 不支持
onwheel WheelEvent MouseWheelEvent
oncopy Event 不支持
oncut Event 不支持
onpaste Event 不支持
onanimationcancel AnimationEvent 不支持
onanimationend AnimationEvent 不支持
onanimationiteration AnimationEvent 不支持
onanimationstart AnimationEvent 不支持
ongotpointercapture PointerEvent GotPointerCaptureEvent
onloadend ProgressEvent LoadEndEvent
onlostpointercapture PointerEvent LostPointerCaptureEvent
onpointercancel PointerEvent PointerCancelEvent
onpointerdown PointerEvent PointerDownEvent
onpointerenter PointerEvent PointerEnterEvent
onpointerleave PointerEvent PointerLeaveEvent
onpointerlockchange Event PointerLockChangeEvent
onpointerlockerror Event PointerLockErrorEvent
onpointermove PointerEvent PointerMoveEvent
onpointerout PointerEvent PointerOutEvent
onpointerover PointerEvent PointerOverEvent
onpointerup PointerEvent PointerUpEvent
onselectionchange Event SelectionChangeEvent
onselectstart Event 不支持
onshow Event 不支持
ontouchcancel TouchEvent TouchCancel
ontouchend TouchEvent TouchEnd
ontouchmove TouchEvent TouchMove
ontouchstart TouchEvent TouchStart
ontransitioncancel TransitionEvent 不支持
ontransitionend TransitionEvent 不支持
ontransitionrun TransitionEvent 不支持
ontransitionstart TransitionEvent 不支持