2024Yew中文使用手册_第1页
2024Yew中文使用手册_第2页
2024Yew中文使用手册_第3页
2024Yew中文使用手册_第4页
2024Yew中文使用手册_第5页
已阅读5页,还剩90页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

YewYewYewRustWebAssemblyUIReactElm等框架经验的开发Yew时会感到得心应手。DOMAPI的调用,从而达JavaScriptNPMJavaScript应用程GitHubissuespageBugs或者是提出新的想法。pullrequestsgoodfirstissues吧!Discordchat非常的热闹,也是一个问问题和解决问题的好地方!YewAppYew项目基于划时代的新技术,非常适合那些希望开发未来基础项目的开发者。接下来YewWeb开发的主流。WebAssembly(Wasm)Rust编译而来。它在浏JavaScript交互。这些在所有的主流浏览器WebAssembly是如何为前端应用提速的,可以查看官值得注意的是,Wasm(目前还)Web应用性能的万金油(原文:ASilverBullet)WebAssemblyDOMAPIJavaScript中调用要慢。但只是暂时性问题的,WebAssemblyInterfaceTypes计划将解决这个问题。如果你Mozilla的这篇佳作。RustRust是一门运行速度超快,并且以他丰富的类型系统和可信赖的所有权模型而闻名的语言。尽管它的学习曲线非常的陡峭,但是带来的回报完全成正比!Rust已经连续五年在StackOverflow开发者调查报告中被评选为最受喜爱的编程语言:2016,2017,2018,2019Rust同样可以用它丰富的类型系统和可信赖的所有权模型来帮助开发者编写出更加安全JavaScriptBugRustBugs都将在项目上线之前的编写阶段被编译器发现。同时不用担心,Rust代码的完Yew没有兴趣,你可能会喜欢这些项目。Percy-“AmodulartoolkitforbuildingisomorphicwebappswithRust+Seed-“ARustframeworkforcreatingweb第一个简单的 Rust库(**重要:**通过传入--lib来创建一个库,而不是一个二进制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(){这份代码通过一 构建了你的根组件,它会显示一个按钮,当你点击按钮时

序,则可以使用最后,在你的应用中新建一个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规范自动生成的APIAPI设API调用返回通常拒绝返回Resultpanic。panic。通过例子学 Yewgithub项目中就包含了各种各样的示例(这些项目在不同程度的维护中)。我们建议你仔细地学习它们,以了解如何使用不同的框架特性.我们在书中有纰漏和错误的时pull-requestsissues♥TodoApp(代办事项CustomComponents(Component组件)Multi-threading(Agents)(多线程Agents)TimerService(定时器Service)NestedComponents(嵌套组件新手模 wasm-MinimalTemplate-使 来构建你的应用并使用你自己的服务器来部署它,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项目设 RustRustWasm

构建工具,请参考官方说明WebAssemblyJavaScript间的相互操作。此外,根据你JavaScript包装代码来让你的应用程序中的RustWasmWebAssemblyCLI 插件搭配使用最佳CLIRustWasmJSWebAssembly之间互操作性的底层工具(

内部被用到)

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

web运行方式,值得安装以运行尚未迁移到支 的示例程序RustWasm工作组RustWasm工作组Yew示例程序的构建脚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应用结合。可以点击这里:::notewasm-pack作为开发工具,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文件中设置的名称。cargocargobuild--targetwasm32-unknown-wasm-bindgenCLI

--out-dirWebAssemblyJavaScript包装器,该包装器将Wasm二进制文件并运行它。这是必要的,因为浏览器目前不能直接加载WebAssemblyJavaScript脚本加载它们。在--out-dir

文件夹中生成文件(

),

(--out-name作为参数传递--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有关用法的详细信息,请查 宏指南

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组件是动态的,可以注册以接收异步信息。update()生命周期方法对于每个消息都会被调HTML元素监听器触发,或者由子组件,Agents,ServicesFutures发送。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有两个关联类型:MessagePropertiesfnmain(){implComponentforMyComponent{typeMessage=Msg;typeProperties=//指的是那些可以被组件用来触发某些副作用的消息。例如,你可能有一 APIUI

fnmain(){enumenumMsg

新组件时。通常的做法是在组件模块中创建一个叫 的结构体并将其用作组件

Properties。如果你希望为根组件指定属性回调 ComponentLinksend_selfFn(IN)->Vec<COMP::Message>Callback<IN>。Fn(INCOMP::Message,Callback<IN>。(这部分可能会独立成为一小章。CallbacksYewservices,agentsFn 包裹以允许被克隆

息。如果一个回调从父组件中通过props提供给子组件,则子组件可以在 生emit,以将消息发送回父组件。在Callbacks。

属性Properties

:::note要派生Properties的类型也必须实现Clone。这同样可以通过使用#[derive(Properties,Clone)]或手动为您的类型实现Clone:::默认情况下,实现 的结构体中的字段是必需的。当缺少了该字段并且中value是该属性的默认值,或者是使 其中的function用来true#[prop_or(true)]。可选属性通常使用Option,其默认值为None。props

Properties的内存/你在Component::viewHtml是有所有权的值(ownedvalues)我们需要获 函数里提供的引用的所有权。这是在将引用传递给组件时隐式克隆propsprops都将被克隆。props(10KB的字符串)

props 中,以便仅克隆一个引用计数的指针,而不是数据本身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函数没有指定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的类型也必须实现Clone。这同样可以通过使用#[derive(Properties,Clone)]或手动为您的类型实现Clone:::Propschildren例中,List组件可以包 组件。有关此模式的真实示例,请查 的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。创建回调的方式取决于你希望你的应用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。更多有关信息,请参见有关选择是选择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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论