当我在开发Yew的组件时,我发现自己总是无法摆脱ReactJS的思维模式。这不在获取中的值时,我脑海里浮现的代码是这样的:
<textarea onChange={(e)=>console.log(e.target.value)}/>
但是在Yew中,最终实现的代码是这样的,对比上面那一行代码,让我大跌眼镜啊。
use wasm_bindgen::{JsCast, UnwrapThrowExt};
use web_sys::{HtmlTextAreaElement, InputEvent};
use yew::{html, Callback, Component, Context, Html, Properties};
fn get_input(input: InputEvent) -> Option<String> {
Some(
input
.target()?
.dyn_into::<HtmlTextAreaElement>()
.ok()?
.value(),
)
}
impl Component for Editor {
...
fn view(&self, ctx: &Context<Self>) -> Html {
let oninput = ctx.link().callback(move |input_event: InputEvent| {
Self::Message::UpdateText(get_input(input_event).unwrap_or("".to_string()))
});
html! {
<div class="content">
<textarea value={self.text.clone()} {oninput}/>
</div>
}
}
}
我们可以看到,在Yew中,也是需要2步才能获取到值:
到这里,textarea中的值也拿到了,本该结束,但我还是想横向扩展一下target对应的具体类型,它们都是web_sys导出的,以方便自己和大家。
HtmlAnchorElement
HtmlAreaElement
HtmlAudioElement
HtmlBaseElement
HtmlBodyElement
HtmlBrElement
HtmlButtonElement
HtmlCanvasElement
HtmlCollection
HtmlDListElement
HtmlDataElement
HtmlDataListElement
HtmlDetailsElement
HtmlDialogElement
HtmlDirectoryElement
HtmlDivElement
HtmlDocument
HtmlElement
HtmlEmbedElement
HtmlFieldSetElement
HtmlFontElement
HtmlFormElement
HtmlFrameElement
HtmlFrameSetElement
HtmlHeadElement
HtmlHeadingElement
HtmlHrElement
HtmlHtmlElement
HtmlIFrameElement
HtmlImageElement
HtmlInputElement
HtmlLabelElement
HtmlLegendElement
HtmlLiElement
HtmlLinkElement
HtmlMapElement
HtmlMediaElement
HtmlMenuElement
HtmlMenuItemElement
HtmlMetaElement
HtmlMeterElement
HtmlModElement
HtmlOListElement
HtmlObjectElement
HtmlOptGroupElement
HtmlOptionElement
HtmlOutputElement
HtmlParagraphElement
HtmlParamElement
HtmlPictureElement
HtmlPreElement
HtmlProgressElement
HtmlQuoteElement
HtmlScriptElement
HtmlSelectElement
HtmlSlotElement
HtmlSourceElement
HtmlSpanElement
HtmlStyleElement
HtmlTableCaptionElement
HtmlTableCellElement
HtmlTableColElement
HtmlTableElement
HtmlTableRowElement
HtmlTableSectionElement
HtmlTemplateElement
HtmlTextAreaElement
HtmlTimeElement
HtmlTitleElement
HtmlTrackElement
HtmlUListElement
HtmlUnknownElement
HtmlVideoElement