I want to try with wasm-pack
, but after several tries, I realized that it was a bad try.
And most parts of the official document uses Trunk, so I was back to Trunk.
Please refer to my post about Trunk.
rustup target add wasm32-unknown-unknown
cargo install trunk
I followed the official “Video page” tutorial.
body
element by default. You can change which part to be injected.#[function_component(NameComponent)]
.impl Component for NameComponent
. Function components are recommended by official, but we will see this impl
way in the next part).yew::start_app::<NameComponent>();
.body
element.html!
macro enable to write JSX-like syntax.{ }
).<> ... </>
) is used.yew::start_app::<NameComponent>();
run the function component NameComponent
.#[derive(Properties)]
to struct. Struct components are data, used by input of function components.Html
type, for example, you can use a function component like this:// in html! macro
<MyPropStruct field1={my_struct.clone()} />
Callback
enum.onclick
attribute:html! {
<p onclick={my_callback}>
{format!("{}: {}", video.speaker, video.title)}
</p>
}
Hooks are functions that let you “hook into” components’ state and/or lifecycle and perform actions.
use_state
yew::functional::UseStateHandle
.set
method set a value to handler.Include a callback function in a Struct property (the type is Callback<T>
).
#[derive(Properties, PartialEq)]
struct VideosListProps {
videos: Vec<Video>,
on_click: Callback<Video>
}
Create a (callback) function component which takes the struct property as a parameter.
#[function_component(VideosList)]
fn videos_list(VideosListProps { videos, on_click }: &VideosListProps) -> Html
Set the callback function. In the function component, emit
method calls the callback function. (More precisely, emit
method send a Message
enum to the component.)
let on_video_select = {
let on_click = on_click.clone();
let video = video.clone();
Callback::from(move |_| {
on_click.emit(video.clone())
})
};
You can set the callback function in HTML by onclick={callback_function}
html! {
<p onclick={on_video_select}>{format!("{}: {}", video.speaker, video.title)}</p>
}
Use the callback in other components:
// Set a hook
let selected_video = use_state(|| None);
// Set a callback function
let on_video_select = {
let selected_video = selected_video.clone();
Callback::from(move |video: Video| {
selected_video.set(Some(video))
})
};
// --snip--
html! {
<>
<h1>{ "RustConf Explorer" }</h1>
<div>
<h3>{"Videos to watch"}</h3>
<VideosList videos={(*videos).clone()} on_click={on_video_select.clone()} />
</div>
{ for details }
</>
}
use reqwasm::http::Request;
trunk serve --proxy-backend=https://yew.rs/tutorial
The terminologies in Yew are quite similar to that of React.
Here is a quote from official README
.
Developers who have experience using JSX in React should feel quite at home when using Yew.
For example, the concept of states, components, props are totally similar to React’s.