2024Yew中文使用手冊_第1頁
2024Yew中文使用手冊_第2頁
2024Yew中文使用手冊_第3頁
2024Yew中文使用手冊_第4頁
2024Yew中文使用手冊_第5頁
已閱讀5頁,還剩90頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

YewYewYewRustWebAssemblyUIReactElm等框架經(jīng)驗的開發(fā)Yew時會感到得心應手。DOMAPI的調(diào)用,從而達JavaScriptNPMJavaScript應用程GitHubissuespageBugs或者是提出新的想法。pullrequestsgoodfirstissues吧!Discordchat非常的熱鬧,也是一個問問題和解決問題的好地方!YewAppYew項目基于劃時代的新技術(shù),非常適合那些希望開發(fā)未來基礎(chǔ)項目的開發(fā)者。接下來YewWeb開發(fā)的主流。WebAssembly(Wasm)Rust編譯而來。它在瀏JavaScript交互。這些在所有的主流瀏覽器WebAssembly是如何為前端應用提速的,可以查看官值得注意的是,Wasm(目前還)Web應用性能的萬金油(原文:ASilverBullet)WebAssemblyDOMAPIJavaScript中調(diào)用要慢。但只是暫時性問題的,WebAssemblyInterfaceTypes計劃將解決這個問題。如果你Mozilla的這篇佳作。RustRust是一門運行速度超快,并且以他豐富的類型系統(tǒng)和可信賴的所有權(quán)模型而聞名的語言。盡管它的學習曲線非常的陡峭,但是帶來的回報完全成正比!Rust已經(jīng)連續(xù)五年在StackOverflow開發(fā)者調(diào)查報告中被評選為最受喜愛的編程語言:2016,2017,2018,2019Rust同樣可以用它豐富的類型系統(tǒng)和可信賴的所有權(quán)模型來幫助開發(fā)者編寫出更加安全JavaScriptBugRustBugs都將在項目上線之前的編寫階段被編譯器發(fā)現(xiàn)。同時不用擔心,Rust代碼的完Yew沒有興趣,你可能會喜歡這些項目。Percy-“AmodulartoolkitforbuildingisomorphicwebappswithRust+Seed-“ARustframeworkforcreatingweb第一個簡單的 Rust庫(**重要:**通過傳入--lib來創(chuàng)建一個庫,而不是一個二進制cargocargonew--libyew-app&&cdyew-將yew和wasm-bindgen添加到您的依賴項中(最新版本請參閱此處name="yew-app"version="0.1.0"authors=["YewAppDeveloper<name@>"]edition="2018"crate-type=["cdylib",yew="0.17"wasm-bindgen=將以下模板復制到您的src/lib.rsfnmain(){usewasm_bindgen::prelude::*;useyew::prelude::*;structModellink:ComponentLink<Self>,value:i64,enumMsgimplComponentforModel{typeMessage=Msg;typeProperties=();fncreate(_:Self::Properties,link:ComponentLink<Self>)->Self{Self{value:0,fnupdate(&mutself,msg:Self::Message)->ShouldRendermatchmatchmsgMsg::AddOne=>self.value+=fnchange(&mutself,_props:Self::Properties)->ShouldRender如果新傳入的屬性(Properties)"true""false".fnview(&self)->Html{html!{<buttononclick=self.link.callback(|_|Msg::AddOne)>{"+1"<p>{self.valuepubfnrun_app(){這份代碼通過一 構(gòu)建了你的根組件,它會顯示一個按鈕,當你點擊按鈕時

序,則可以使用最后,在你的應用中新建一個static文件夾,然后將一個index.html文件添加到這個文件夾mkdirmkdir<!doctype<html<metacharset="utf-<title>YewSample<scriptimportinitfrom"./wasm.js"運行你的應用程序最好是使用wasm-pack來啟動和運行應用。如果還未安裝wasm-packcargocargoinstallwasm-wasm-packwasm-packbuild--targetweb--out-namewasm--out-dir./staticWebAssembly,JavaScriptWebAssembly二進制文件并運行Web服務器為./staticcargo+nightlyinstallminiserveminiservecargo+nightlyinstallminiserveminiserve./static--indexindex.html選擇web-sys還是 Yew

cratesRustAPI之間的綁定。當 添加到你的cargo依賴時,你需要選擇它們其中之一`web-sys`yew="0.17"選擇yew={version="0.17",package="yew-stdweb"web-sysRustWasm工作組fnmain(){//web-letwindow:web_sys::Window=web_sys::window().expect("windownotavailable");window.alert_with_message("hellofromwasm!").expect("alertfailed");//letwindow:stdweb::web::Window=stdweb::web::window();window.alert("hellofromwasm!");stdweb搭配jsuseusestdweb::unstable::TryFrom;usestdweb::web::Window;letwindow_valstdweb::Valuejs!returnwindow里面使用JSletwindow=Window::try_from(window_val).expect("conversiontowindowfailed");window.alert("hellofromwasm!");crateAPI

crate的最小化,最好選擇其RustWasm工作組API覆RustAPIWebIDL規(guī)范自動生成的APIAPI設(shè)API調(diào)用返回通常拒絕返回Resultpanic。panic。通過例子學 Yewgithub項目中就包含了各種各樣的示例(這些項目在不同程度的維護中)。我們建議你仔細地學習它們,以了解如何使用不同的框架特性.我們在書中有紕漏和錯誤的時pull-requestsissues?TodoApp(代辦事項CustomComponents(Component組件)Multi-threading(Agents)(多線程Agents)TimerService(定時器Service)NestedComponents(嵌套組件新手模 wasm-MinimalTemplate-使 來構(gòu)建你的應用并使用你自己的服務器來部署它,NobellsorwhistlesWebpackTemplate-使

程,同時你的應用的入口應該使 標記出來

crate-type“cdylibname="yew-app"version="0.1.0"authors=["YewAppDeveloper<name@>"]edition="2018"crate-type=#使用web_sysyew="0.17"#或是使用#yew={version="0.17",package="yew-stdweb"}wasm-bindgen="0.2"ParcelTemplateParcel項目設(shè) RustRustWasm

構(gòu)建工具,請參考官方說明WebAssemblyJavaScript間的相互操作。此外,根據(jù)你JavaScript包裝代碼來讓你的應用程序中的RustWasmWebAssemblyCLI 插件搭配使用最佳CLIRustWasmJSWebAssembly之間互操作性的底層工具(

內(nèi)部被用到)

JavaScriptWebAssembly程序。但是,直接使用它也是可能的并且可以 指南上找到更多信息

web運行方式,值得安裝以運行尚未遷移到支 的示例程序RustWasm工作組RustWasm工作組Yew示例程序的構(gòu)建腳Yew示例程序的使用 cargoinstall--lockedtrunkcargocargoinstall--lockedtrunkcargoinstallwasm-bindgen-cliCheckout“Buildasampleapp”forashortguideonhowtobuildYewappswithYoucanalsoseeitinactionbylookingatourexamples,allofwhicharebuiltwithTrunkbuildsyourappbasedon filewhichservesasaconfigfileofUnlikewasm-pack,thistoolisactuallydesignedtobuildapps.Thismeansyoudon’tto

asalibrarytargetandyoucanuse

functionasanentryTobuildasimpleYewappyoujustneed fileattherootofyour<!DOCTYPE<!DOCTYPE<metacharset="utf-8"<title>YewTheTrunkCLIprovidesseveralusefulcommandsbutduringdevelopment certainlythemostusefulone.Itrunsalocalserverforyouandautomaticallyrebuildstheappwhenitdetectschanges.trunkWhenyou’rereadytoreleaseyourapp,youcanjustruntrunkbuild--trunkThissummaryheredoesn’tnearlycoverallofTrunk’sfeatures,besuretocheckoutthe使用wasm- RustWasmWebAssembly

Webpack插件JavaScript應用結(jié)合??梢渣c擊這里:::notewasm-pack作為開發(fā)工具,Cargo.toml

cargocargoinstallwasm-

WebAssemblyJavaScriptwasm-packwasm-packbuild--targetRollup的更多信息,請查看這篇rolluprollup./main.js--formatiife--filePython服務器來將項目部署pythonpython-mhttp.server使用wasm- cargocargoinstallwasm-bindgen-的。那么輸出文件的路徑為target/wasm32-unknown-unknown/debug/yew-app.wasm。如果您將crateWasm文件的名稱將不是yew-app.wasm,而是您在Cargo.toml文件中設(shè)置的名稱。cargocargobuild--targetwasm32-unknown-wasm-bindgenCLI

--out-dirWebAssemblyJavaScript包裝器,該包裝器將Wasm二進制文件并運行它。這是必要的,因為瀏覽器目前不能直接加載WebAssemblyJavaScript腳本加載它們。在--out-dir

文件夾中生成文件(

),

(--out-name作為參數(shù)傳遞--out-namewasm-bindgenwasm-bindgen--targetweb--out-dirstatic--out-namewasmtarget/wasm32-unknown-Pythonpythonpython-mhttp.serverwasm-bindgen使用cargo- CargowebwebCargoweb應Emscripten目標代碼的工具鏈。點擊cargocargoinstallcargo-cargocargowebcargocargoweb:::note對 的目標代碼,你需要安裝EmscriptenSDK。組件 YewDOM

trait:::importantcontribute為我們的文檔做出貢獻:添加組件的生命周期圖示

fnmain(){pubstructMyComponent{props:Props,link:fnmain(){pubstructMyComponent{props:Props,link:implComponentforMyComponent{typeProperties=Props;//fncreate(props:Self::Properties,link:ComponentLink<Self>)->Self{MyComponent{props,link}//

方法中聲明它的布局。Yew

HTMLSVGReactJSXRustfnmain(){implComponentforMyComponent//fnview(&self)->Htmlletonclick=self.link.callback(|_|Msg::Click);html!{<buttononclick=onclick>{ps.button_text有關(guān)用法的詳細信息,請查 宏指南

Yew

fnmain(){usestdweb::web::html_element::InputElement;usestdweb::web::IHtmlElement;usepubstructMyComponent{node_ref:NodeRef,implComponentforMyComponent//fnview(&self)->Html{html!{<inputref=self.node_ref.clone()type="text"fnrendered(&mutself,first_render:bool){iffirst_render{ifletSome(input)=self.node_ref.cast::<InputElement>(){:::tipnote組件是動態(tài)的,可以注冊以接收異步信息。update()生命周期方法對于每個消息都會被調(diào)HTML元素監(jiān)聽器觸發(fā),或者由子組件,Agents,ServicesFutures發(fā)送。fnmain(){pubenumMsg{implComponentforMyComponent{typeMessage=Msg;//fnupdate(&mutself,msg:Self::Message)->ShouldRender{matchmsg{Msg::SetInputEnabled(enabled)=>ifself.input_enabledenabledself.input_enabled=enabled;true//重新渲染}elsefnmain(){implComponentforMyComponent//fnchange(&mutself,props:Self::Properties)->ShouldRender{ifps!=props{ps=props;}elseDOM上被卸載后,Yew

trait有兩個關(guān)聯(lián)類型:MessagePropertiesfnmain(){implComponentforMyComponent{typeMessage=Msg;typeProperties=//指的是那些可以被組件用來觸發(fā)某些副作用的消息。例如,你可能有一 APIUI

fnmain(){enumenumMsg

新組件時。通常的做法是在組件模塊中創(chuàng)建一個叫 的結(jié)構(gòu)體并將其用作組件

Properties。如果你希望為根組件指定屬性回調(diào) ComponentLinksend_selfFn(IN)->Vec<COMP::Message>Callback<IN>。Fn(INCOMP::Message,Callback<IN>。(這部分可能會獨立成為一小章。CallbacksYewservices,agentsFn 包裹以允許被克隆

息。如果一個回調(diào)從父組件中通過props提供給子組件,則子組件可以在 生emit,以將消息發(fā)送回父組件。在Callbacks。

屬性Properties

:::note要派生Properties的類型也必須實現(xiàn)Clone。這同樣可以通過使用#[derive(Properties,Clone)]或手動為您的類型實現(xiàn)Clone:::默認情況下,實現(xiàn) 的結(jié)構(gòu)體中的字段是必需的。當缺少了該字段并且中value是該屬性的默認值,或者是使 其中的function用來true#[prop_or(true)]??蛇x屬性通常使用Option,其默認值為None。props

Properties的內(nèi)存/你在Component::viewHtml是有所有權(quán)的值(ownedvalues)我們需要獲 函數(shù)里提供的引用的所有權(quán)。這是在將引用傳遞給組件時隱式克隆propsprops都將被克隆。props(10KB的字符串)

props 中,以便僅克隆一個引用計數(shù)的指針,而不是數(shù)據(jù)本身fnmain(){usestd::rc::Rc;useyew::Properties;#[derive(Clone,PartialEq)]pubenumLinkColor{implDefaultforLinkColor{fndefault()->Self{#[derive(Properties,Clone,PartialEq)]pubstructLinkProps{href:text:///鏈接的顏色color:LinkColor,如果為None,則viewsize:當view函數(shù)沒有指定active,其默認為active:bool, GeneralMostofthetime,whenallowingacomponenttohavechildren,youdon’tcarewhattypeofchildrenthecomponenthas.Insuchcases,thebelowexamplewillsuffice.fnmain(){use#[derive(Properties,Clone)]pubstructListProps{pubchildren:pubstructList{props:ListProps,implComponentforListtypeProperties=//fnview(&self)->Html{html!{<div{ps.children.iter()AdvancedIncaseswhereyouwantonetypeofcomponenttobepassedaschildrentoyourcomponent,youcanuseyew::html::ChildrenWithProps<T>.fnmain(){useyew::html::ChildrenWithProps;useyew::prelude::*;//#[derive(Properties,#[derive(Properties,Clone)]pubstructListProps{pubchildren:pubstructList{props:ListProps,implComponentforListProps{typeProperties=ListProps;//fnview(&self)->Html{html!{<div{ps.children.iter()Ofcourse,sometimesyoumightneedtorestrictthechildrentoafewdifferentcomponents.Inthesecases,youhavetogetalittlemorehands-onwith crateisusedhereforbetterergonomics.Ifyoudon’twanttouseit,canmanually foreachfnmain(){useuseuseyew::virtual_dom::{VChild,VComp//`derive_more::From`implements`From<VChild<Primary>>`//`From<VChild<Secondary>>`for`Item`automatically!#[derive(Clone,derive_more::From)]pubenumItem{//Now,weimplment`Into<Html>`sothatyewknowshowtorender`Item`.implInto<Html>forItem{fninto(self)->Html{matchself{Self::Primary(child)=>o(),Self::Secondary(child)=>o(),#[derive(Properties,Clone)]pubstructListProps{pubchildren:pubstructList{props:ListProps,implComponentforListtypeProperties=//fnview(&self)->Html{html!{<div{ps.children.iter() HTML

DOMfnmain(){在createfnmain(){在createself.node_ref=在viewhtml!<div在updatelethas_attributes=使用html! HTMLSVGReactJSX,將會html! html!

常量必須始終被引號括起來并被包含在大括號里:html"HelloWorld:::notehtml!宏可以輕松達到編譯器的默認遞歸限制。如果遇到編譯錯誤,建議增大其crate使用這樣的屬性#![recursion_limit="1024"](lib.rs或main.rs也是同理)處官方文檔StackOverflow問答組

trait

fnmain(){<MyComponent<MyComponentprop1="lorem"prop2="ipsum"同時提供全套的<MyComponentwithprops

fnmain(){html!{<h4>{"Hi"<div>{"Hello"fnmain(){pubstructpubstructProps{pubchildren:implComponentforContainer{typeProperties=Props;//fnview(&self)->Html{html!{<div{self.0.children.clone():::note要派生Properties的類型也必須實現(xiàn)Clone。這同樣可以通過使用#[derive(Properties,Clone)]或手動為您的類型實現(xiàn)Clone:::Propschildren例中,List組件可以包 組件。有關(guān)此模式的真實示例,請查 的yew

fnmain(){html!{<ListItemvalue="a"<ListItemvalue="b"<ListItemvalue="c"fnmain(){pubstructpubstructProps{pubchildren:implComponentforList{typeProperties=Props;////fnview(&self)->Html{forself.0.children.iter().map(|mutitem|{ps.value=format!("item-{}",ps.value);元 <.../>fnmain()fnmain(){html!{<divfnmain(){html!{<divid="my_div"fnmain(){html!{<inputid="my_input"fnmain(){html!{<inputid="my_input":::note如,html!{<divclass="placeholder:::HTMLSVGfnfnmain(){html!{<divdata-<div<spanclass="child"<labelfor="first-name">{"FirstName"<inputtype="text"id="first-name"value="placeholder"<inputtype="checkbox"checked=true<textareavalue="writeastory"<select<optionselected=truedisabled=falsevalue="">{"Selected"<optionselected=falsedisabled=truevalue="">{"Unselected"fnmain(){html!{<svgwidth="149"height="147"viewBox="00149147"fill="none"<pathd="M60.577613.8268L51.867342.6431L77.747537.331L60.577613.8268Z"<pathd="M108.36194.9937L138.70890.686L115.34269.8642"stroke="black"stroke-<g<circlecx="75.3326"cy="73.4918"r="55"<circlecx="75.3326"cy="73.4918"r="52.5"stroke="black"stroke-<circlecx="71"cy="99"r="5"fill="white"fill-opacity="0.75"stroke="black"<filterid="filter0_d"x="16.3326"y="18.4918"width="118"height="118"<feGaussianBlur<feColorMatrixin="SourceAlpha"type="matrix"values="0000000000fnmain(){html!{<divfnmain()fnmain(){html!{<divclass="containercenter-fnmain(){html!{<divclass=format!("{}-container",fnmain(){html!{<divfnmain(){html!{<divclass=("class-1","class-fnmain(){html!html!<divclass=vec!["class-1","class-Callback。創(chuàng)建回調(diào)的方式取決于你希望你的應用fnmain(){fnmain(){structMyComponentlink:enumMsgimplComponentforMyComponent{typeMessage=Msg;typeProperties=fncreate(_:Self::Properties,link:ComponentLink<Self>)->Self{MyComponent{link}fnupdate(&mutself,msg:Self::Message)->ShouldRender{matchmsg{Msg::Click=>處理fnview(&self)->Html從組件linkletclick_callback=self.link.callback(|_:ClickEvent|Msg::Click);html!{<button{"Clickme!"fnmain(){structstructMyComponentworker:implComponentforMyComponent{typeMessage=();typeProperties=fncreate(_:Self::Properties,_:ComponentLink<Self>)->Self{MyComponent{worker:fnupdate(&mutself,_:Self::Message)->ShouldRender{fnview(&self)->Htmlworkerletclick_callback=self.worker.callback(|_:ClickEvent|WorkerMsg::Process);html!{<button{"Clickme!"fnmain(){structimplComponentforMyComponent{typeMessage=();typeProperties=fncreate(_:Self::Properties,_:ComponentLink<Self>)->Self{fnupdate(&mutself,_:Self::Message)->ShouldRender{fnview(&self)->Htmlletclick_callback=Callback::from(||{html!<button{"Clickme!":::noteyew與web-sys一起使用時,才應使用web-sys的事件類型(默認情況下啟用)。如果您使用的是yew-stdwebcrate,請使用stdweb。更多有關(guān)信息,請參見有關(guān)選擇是選擇web-sys還是stdweb::::::note下表中提到的所有事件類型都已在yew::events或stdwebcrateyew::events中的類型更容易確保版本兼容Yew:::web_sysstdweb The

canbeusedtodealwithHTMLWhenpushingastringtothe ensuresthatthereisoneelementforclassevenifasinglestringmightcontainmultiplecanalsobemergedby

(i.e.classes1.extend(classes2))

classes1.push(classes2)).Infact,anythingthatimplementspushnewclassestotheset.

canbeusedThe isaconvenientmacrothatcreatesonesingleClasses.Itsacceptsacommaseparatedlistofexpressions.TheonlyrequirementisthateveryexpressionimplementsInto<Classes>.fnfnmain(){html!{<divfnmain(){html!{<divclass=classes!("class-1","class-fnmain(){letmy_classes=String::from("class-1class-html!<divfnfnmain(){html!{<divclass=classes!(Some("class"))fnmain(){html!{<divclass=classes!(vec!["class-1","class-fnmain(){letmy_classes=["class-1","class-html!<divComponentsthatacceptfnmain(){use#[derive(Clone,Properties)]structProps{class:Classes,fill:bool,children:Children,structMyComponent{props:Props,implimplComponentforMyComponent{typeProperties=Props;//fnview(&self)->Html{letProps{}=&ps;html!{{children.clone()Theexamplemakesuseoftheboolinatorcratetoconditionallyaddthe“my-fill-classbasedon boolean列 fnfnmain(){html!{fnmain(){/*錯誤:只允許一個html根元素html!Yewhtmlfnfnmain(){html!{<ulclass="item-fnmain(){html!{<ulclass="item-{ps.items.iter().map(renderItem)常量和表達

TextDOM

Rust理。這一點上,YewHTMLHTMLfnmain(){lettext="loremipsum";<div>{"dolorHTML

Rustfnmain(){html!{ifshow_link{html!{<a}else{html!{}fnmain(){letshow_link=letmaybe_display_link=move||->Html{ifshow_link{html!<a}else{html!{}html! :::note ThefetchservicecanbeusedtomakeHTTPrequeststoaserver.Thisenablesapplicationstocommunicatewithexternalservices.:::noteYoumightfindithelpfultoreadthedocumentationfortheformatmodulebeforereadingthispage.:::MakingBuildingYewre-exports

structfrom

cratethatisusedto‘build’orbeforetheycanbedispatchedtoaserver.Thevalueoftherequestbodyor

aretypealiasesforthe

fnmain(){pubtypeText=Result<String,Error>;pubtypeBinary=Result<Vec<u8>,Error>;HereiswhatatypicalGETrequestwilllookfnmain(){useuseletget_request=.expect("CouldnotbuildthatHereiswhatatypicalPOSTrequestwilllookfnmain(){useserde_json::json;useyew::format::Json;useletpost_request=.header("Content-Type",.expect("Couldnotbuildthat:::noteNotethatthestructsintheformatmoduletakereferencestovaluesinsteadvalues notT).Dispatchingusing

providesabindingtothe

API.Requestscanbesentshouldbeusedwhencookiesneedtobesentwithaacceptstwoparameters: objectandaCallback.iscalledoncetherequesthascompletedallowingyoutohandlethedatareturnedfromtherequest.ThecallbackyoupassneedstotakeasingleparameteroftypewhereTisthebodyoftheresponse.YewneedstobeabletoparsetheresponsetocreateaninstanceofthedatatypeTsoitneedstoimplementFrom<Binary>.TofetchdatainabinaryformatyoushoulduseratherthanFetchService::fetch.FormatDataType<Result<T,:::noteBecausesomethingcouldgowrongtryingtodeserializeFormatDataType<Result<T,

FormatDataType<T>)wheremodule(e.g.Json).

isusedasaplaceholderforanytypeintheThismeansthatyourcallbacksshouldlookfnmain(){ratherfnmain(){:::cautionIf isdroppedbeforetherequesthasfinished,itwillbeMakesuretokeepitaround!:::importantIfyoukeepgettinganerrorsayingthat“theoperationwasaborted”or“Error408”thismightbebecausetheCORSheadersofthewebsiteyouaretryingtoaccessarenotsetcorrectly.PleaseseethelinkedarticlefromMozillaabouthowtoresolvetheseerrors.:::AnillustratedexampleofhowtofetchdatafromanAPIgivinginformationabouttheISS’s(InternationalSpaceStation)locationisgivenbelow.fnmain(){//requirestheserdeandanyhowuseuseyew::{format::{Json,Nothing},useyew_services::fetch::{FetchService,FetchTask,Request,#[derive(Deserialize,Debug,Clone)]pubstructISSPosition{latitude:String,longitude:String,#[derive(Deserialize,Debug,Clone)]pubstructISS{message:String,timestamp:i32,iss_position:ISSPosition,pubenumMsg{pubstructFetchServiceExample{fetch_task:Option<FetchTask>,iss:Option<ISS>,link:ComponentLink<Self>,error:Option<String>,///SomeofthecodetorendertheUIissplitoutintosmallerfunctionsheretomake///cleanerandshowsomeusefuldesignpatterns.implFetchServiceExample{fnview_iss_location(&self)->Html{matchself.iss{Some(refspace_station)=>{html!{

<p>{"TheISSisat:"<p>{format!("Latitude:{}",space_station.iss_position.latitude)<p>{format!("Longitude:{}",None=>html!<buttononclick=self.link.callback(|_|{"WhereistheISS?"fnview_fetching(&self)->Html{ifself.fetch_task.is_some(){html!{<p>{"Fetchingdata..."}</p>}elsehtml!{<p></p>fnview_error(&self)->HtmlifletSome(referror)=self.error{html!{<p>{error.clone()}</p>}}elsehtml!implComponentforFetchServiceExample{typeMessage=Msg;typeProperties=fncreate(_props:Self::Properties,link:ComponentLink<Self>)->Self{Self{fetch_task:None,iss:None,error:None,fnchange(&mutself,_props:Self::Properties)->bool{fnupdate(&mutself,msg:Self::Message)->bool{useMsg::*;matchmsgGetLocation=>//1.buildtheletrequest=Request::get("/iss-.expect("Couldnotbuild//2.constructacallbackletcallback=.callback(|response:Response<Json<Result<ISS,anyhow::Error>>>|{letJson(data)=o_body();//3.passtherequestandcallbacktothefetchlettask=FetchService::fetch(request,callback).expect("failedtostart//4.storethetasksoitisn'tcanceledimmediatelyself.fetch_task=Some(task);//wewanttoredrawsothatthepagedisplaysa'fetching...'messageto//soreturn'true'ReceiveResponse(response)=>{matchresponse{Ok(location)=>self.iss=Err(error)=>self.error=self.fetch_task=//wewanttoredrawsothatthepagedisplaysthelocationoftheISS//'fetching...'fnview(&self)->Html{html!{{self.view_fetching(){self.view_iss_location(){self.view_error()DebuggingMostbrowsers’developertoolshavea“network”panelwhichcanbeusedtoHTTPrequests.Thiscanbeusedtogaininsightintowhatrequestsarebeingmade,thedatabeingsenttotheserver,aswellastheresponse.TheRustWasmBookalsocontainsusefuldebuggingtipsforWasmFurtherTheAPIdocumentationThedashboardexample.TheRustWasmBookondebuggingWasmapplications :::importantcontribute為我們的文檔做出貢獻:深入解釋格式模塊Function Function:::warningWe’restillworkingonfunctioncomponentsandHooks.They’renotquitereadytobeusedyet.Ifyou’dliketohelpout,takealookattheprojectboardforalistofthingsthatstillneedtobedone.:::Functioncomponentsareasimplifiedversionofnormalcomponents.TheyconsistofasinglefunctionthatreceivespropsanddetermineswhatshouldberenderedbyreturningHtml.Basically,it’sacomponentthat’sbeenreducedtojust Onitsownthatwouldbequitelimitingbecauseyoucanonlycreatepurecomponents,butthat’swhereHookscomein.HooksallowfunctioncomponentstousestateandotherYewfeatureswithoutimplementingCreatingfunction

Theeasiestwaytocreateafunctioncomponentistoaddtheattributetoafunction.fnmain(){fnhello_world()->Html{html!{"Helloworld"UndertheFunctioncomponentsconsistsoftwoparts.First,

traitwhichcomparableto traitbutitonlyhasasinglemethodcalledrun.Thepartis

structwhichwrapsaround

typeanditintoanactualComponent. attributeessentiallyjustforyouandexposesitwrappedinHooksaresimplyfunctionsthatletyou“hookinto”components’stateand/orlifecycleandperformactions.Yewcomeswithafewpre-definedHooks.Youcanalsocreateyourown.Pre-definedYewcomeswiththefollowingpredefinedCustomTherearecaseswhereyouwanttodefineyourownHooksforreasons.YewallowsyoutodefineyourownHookswhichletsyouextractyourpotentiallystatefullogicfromthecomponentintoreusablefunctions.SeetheDefiningcustomhookssectionformore turnsanormalRustfunctionintoafunctionFunctionswiththeattributehaveto andmaytakeasingleparameterfortypeofpropsthecomponentshouldaccept.Theparametertypeneedstobereferencetoatypewhich

(ex.props:&MyProps).Iffunctiondoesn’thaveanyparameterstheresultingcomponentdoesn’tacceptanyTheattributedoesn’treplaceyouroriginalfunctionwithacomponent.Youneedtoprovideanameasaninputtotheattributewhichwillbetheidentifierofthecomponent.Assumingyouhaveafunction andyouaddtheyoucanusethecomponentlikefnmain(){html!{<ChatContainer/>fnmain(){#[derive(Properties,Clone,PartialEq)]pubstructRenderedAtProps{pubtime:pubfnrendered_at(props:&RenderedAtProps)->Html{html!{<b>{"Renderedat:"{&props.timefnmain(){fnapp()->Html{let(counter,set_counter)=use_state(||letonclick=letcounter=Rc::clone(&counter);Callback::from(move|_|set_counter(*counter+1))html!<buttononclick=onclick>{"Incrementvalue"<b>{"Currentvalue:"{counterGenericfunctiongeneric

attributealsoworkswithgenericfunctionsforfnmain(){#[derive(Properties,Clone,PartialEq)]pubstructProps<T>whereT:Clone+data:pubfnmy_generic_component<T>(props:&Props<T>)->HtmlwhereT:Clone+PartialEq+Displayhtml!{props.data//usedlikethishtml!{<MyGenericComponent<i32><MyGenericComponent<i32>data=123//orhtml!{<MyGenericComponent<Foo>data=fooPre-defined isusedtomanagestateinafunctioncomponent.Itreturns whichDerefstothecurrentvalueandprovides methodtoupdatetheThehooktakesafunctionasinputwhichdeterminestheinitialstate.Thisvalueremainsup-to-dateonsubsequentrenders.fnmain(){fnmain(){fnstate()->Html{letcounter=use_state(||0);letonclick={letcounter=counter.clone();Callback::from(move|_|counter.set(*counter+1))html!<buttononclick=onclick>{"Incrementvalue"<b>{"Currentvalue:"{*counterisusedforobtainingamutablereferencetoavalue.ItsstatepersistsacrossItisimportanttonotethatyoudonotgetnotifiedofstatechanges.Ifyouneedthecomponenttobere-renderedonstatechange,considerusinguse_state.fnmain(){fnmain(){fnref_hook()->Html{let(message,set_message)=use_state(||"".to_string());letmessage_count=use_ref(||0);letonclick=Callback::from(move|e|{letwindow=yew::utils::window();if*message_count.borrow_mut()>3{window.alert_with_message("Messagelimitreached");}else*message_count.borrow_mut()+=1;window.alert_with_message("Messagesent");letonchange=Callback::from(move|e|{ifletChangeData::Value(value)=e{html!<inputonchange=onchangevalue=message<buttononclick=onclick>{"Send"isanalternativetouse_state.Itisusedtohandlecomponent’sstateandisusedwhencomplexactionsneedstobeperformedonsaidstate.Itacceptsareducerfunctionandinitialstateand pointingtothestate,anddispatchfunction.ThedispatchfunctiontakesoneargumentoftypeAction.Whencalled,theactionandcurrentvaluearepassedtothereducerfunctionwhichcomputesanewstatewhichisreturned,andthecomponentisre-rendered.Forlazyinitialization,consider fnmain(){fnreducer()->Html{///reducer'sActionenumAction{///reducer'sStatestructCounterState{counter:letcounter=//thereducer|prev:Rc<CounterState>,action:Action|CounterState{counter:matchaction{Action::Double=>prev.counter*2,Action::Square=>prev.counter*prev.counter,//initialstateCounterState{counter:1},letdouble_onclick=letcounter=Callback::from(move|_|letsquare_onclick=letcounter=Callback::from(move|_|html!<divid="result">{counter.counter<buttononclick=double_onclick>{"Double"<buttononclick=square_onclick>{"Square"butwithinitargument.TheHookispassedtheinitialstatewhichispasseddowntoreturnsthisstate.

functionwhichinitializesthestateandreturnsit.ThehookThisisusefulforlazyinitializationwhereitisbeneficialnottoperformexpensivecomputationup-front.fnmain(){fnmain(){letcounter=//reducer|prev:Rc<CounterState>,action:i32|CounterState{counter:prev.counter+action,0,//initial|initial:i32|CounterState{//initmethodcounter:initial+10,isusedforhookingintothecomponent’slifecycle.Similar from takesafunctionwhichiscalledaftertherenderTheinputfunctionhastoreturnaclosure,thedestructor,whichiscalledwhenthecomponentisdestroyed.Thedestructorcanbeusedtocleanuptheeffectsintroducedanditcantakeownershipofvaluestodelaydroppingthemuntilthecomponentisfnmain(){fneffect()->Html{let(counter,set_counter)=use_state(||letcounter=counter.clone();use_effect(move||{//MakeacalltoDOMAPIaftercomponentisrenderedyew::utils::document().set_title(&format!("Youclicked{}times",counter));//Performthe||yew::utils::document().set_title("Youclicked0letonclick=letcounter=Rc::clone(&counter);Callback::from(move|_|letcounter=Rc::clone(&counter);Callback::from(move|_|set_counter(*counter+1))html!<buttononclick=onclick>{format!("Incrementto{}",counter)Sometimes,it’sneededtomanuallydefinedependenciesforuse_effect.Insuchcases,weuseuse_effect_with_deps.fnmain(){move|_|{//||(),// mustimplementisusedforconsumingcontextsinfunctionfnmain(){///App#[derive(Clone,Debug,PartialEq)]structTheme{foreground:String,background:///Maincomponentpubfnapp()->Html{letctx=use_state(||Themeforeground:foreground:"#000000".to_owned(),background:html!//`ctx`istype`Rc<UseStateHandle<Theme>>`whileweneed`Theme`sowederef//Itderefsto`&Theme`,hencethe<ContextProvider<Theme>//Everychildhereandtheirchildrenwillhaveaccesstothis<Toolbar///The///Thiscomponenthasaccesstothecontextpubfntoolbar()->Html{html!{<ThemedButton///Buttonplacedin///Asthiscomponentisachildof`ThemeContextProvider`inthecomponenttree,italsohpubfnthemed_button()->Htmllettheme=use_context::<Theme>().expect("noctxhtml!<buttonstyle=format!("background:{};color:{};",theme.background,{"Clickme!"Custom DefiningcustomComponent’sstatefullogiccanbeextractedintousablefunction

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論