Xavientois 4a14d0f0a4
Add requirement for braces around most props (#1939)
* Limit the properties to literals and brace-enclosed expressions

* Update examples with new syntax

* Update packages/yew-macro/src/props/prop.rs

Co-authored-by: Teymour Aldridge <42674621+teymour-aldridge@users.noreply.github.com>

* Fix lints and strip braces around single expressions

* Update docs with new prop syntax

* Add some test cases for new syntax

* Ensure all tests are passing

* Clean up missed code

* Update tests

* Update reverted docs

* Revert versioned docs

* Fix optional attributes paragraph

* Remove accidentally added files

* Remove accidentally added french docs

* Update packages/yew-macro/src/props/prop.rs

Co-authored-by: mc1098 <m.cripps1@uni.brighton.ac.uk>

* Fix forgotten braces and test cases

* Revert i18n old docs

* Revert translated docs

* Remove suggested fix in favour of more succinct error message

* Update errors after rebase

* Remove files accidentally added while rebasing

* Fix merge conflicts

Co-authored-by: Teymour Aldridge <42674621+teymour-aldridge@users.noreply.github.com>
Co-authored-by: mc1098 <m.cripps1@uni.brighton.ac.uk>
2021-07-18 18:54:21 +02:00

21 KiB

title description
Elements Both HTML and SVG elements are supported

タグ構造

要素のタグは<... />のような自己完結タグか、開始タグに対応した終了タグを持っている必要があります。

html! {
  <div id="my_div"></div>
}
html! {
  <div id="my_div"> // <- MISSING CLOSE TAG
}
html! {
  <input id="my_input" />
}
html! {
  <input id="my_input"> // <- MISSING SELF-CLOSE
}

:::note 便利さのために、_普通は_終了タグを必要とする要素は自己完結タグとすることができます。 例えばhtml! { <div class="placeholder" /> }と書くのは有効です。 :::

複雑にネストしたHTMLやSVGのレイアウトを書くのには以下のようにするのが楽です: **

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>
}
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>
}

クラス

要素へのクラスを特定する便利なやり方はたくさんあります:

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

リスナー

リスナー属性はクロージャのラッパーであるCallbackに渡される必要があります。 コールバックをどのように作るかはアプリをリスナーイベントにどう反応させたいかによります。

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 => {
                // Handle Click
            }
        }
    }

    fn view(&self) -> Html {
        // Create a callback from a component link to handle it in a component
        let click_callback = self.link.callback(|_: ClickEvent| Msg::Click);
        html! {
            <button onclick={click_callback}>
                { "Click me!" }
            </button>
        }
    }
}
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 {
        // Create a callback from a worker to handle it in another context
        let click_callback = self.worker.callback(|_: ClickEvent| WorkerMsg::Process);
        html! {
            <button onclick={click_callback}>
                { "Click me!" }
            </button>
        }
    }
}
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 {
        // Create an ephemeral callback
        let click_callback = Callback::from(|| {
            ConsoleService::new().log("clicked!");
        });

        html! {
            <button onclick={click_callback}>
                { "Click me!" }
            </button>
        }
    }
}

イベントの型

:::note 以下のテーブルではyewweb-sysと使う場合 (デフォルトでは使うようになっている) web-sysのイベントの型が使われるべきです。 yew-stdwebクレートを使う場合はstdwebのイベントの型を使用してください。 詳細についてはweb-sysstdwebをどちらを使うべきかについてのドキュメントをご確認ください。 :::

:::note 以下のテーブルにある全てのイベントの型はyew::eventsで再エクスポートされています。 All the event types mentioned in the following table are re-exported under yew::events. Using the types from yew::events makes it easier to ensure version compatibility than if you were to manually include web-sys or stdweb as dependencies in your crate because you won't end up using a version which conflicts with the version Yew specifies. :::

イベント名 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 サポート無し