yew
環境
code:toml
edition = "2018"
yew = "0.16.2"
wasm-bindgen = "0.2.63"
Lifecycle
Styling
styled-yewというものがあるらしい。
Command
$ wasm-pack build --dev --target web --out-name wasm --out-dir ./static
--devを抜くとPrductionBuild
Stringの描画
{ &self.text }基本 str 形式で描画するが受け取る際は、String
初期化の際は"hogehoge".to_string()とかすればいい。
JSのArray型
Vec<T>初期化時はvec![]とかで良いと思う。
描画する際はiterをforで回すため
{ for self.list_item.iter().map(imte_mapper) }
という風に記述する必要がある。
双方向バインディングサンプル
code:rust
use yew::prelude::*;
struct Model {
text: String,
}
enum Msg {
SetTitle(String),
}
impl Component for Model {
type Message = Msg;
type Properties = ();
// constructor
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
// data
Self {
link,
value: 0,
console: ConsoleService::new(),
title: "hogehoge".to_string(),
}
}
// handler
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::SetTitle(title) => self.title = title,
}
true
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
// Should only return "true" if new properties are different to
// previously received properties.
// This component has no properties so we will always return "false".
false
}
fn view(&self) -> Html {
html! {
<>
<input
type="text"
oninput=self.link.callback(|e: InputData| Msg::SetTitle(e.value))
value=self.text
/>
<p>{format!("{}", self.text).as_str()}</p>
</>
}
}
}
カスタムコンポーネントの定義
code:rs
use yew::prelude::*;
pub struct Button {
link: ComponentLink<Self>,
title: String,
onsignal: Callback<()>,
}
pub enum Msg {
Clicked,
}
pub struct Props {
pub title: String,
pub onsignal: Callback<()>,
}
impl Component for Button {
type Message = Msg;
type Properties = Props;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Button {
link,
title: props.title,
onsignal: props.onsignal,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Clicked => {
self.onsignal.emit(());
}
}
false
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
self.title = props.title;
self.onsignal = props.onsignal;
true
}
fn view(&self) -> Html {
html! {
<button
onclick=self.link.callback(|_| Msg::Clicked)
{ &self.title }
</button>
}
}
}