mirror of
https://github.com/DioxusLabs/dioxus
synced 2024-11-27 06:30:20 +00:00
docs: more docs
This commit is contained in:
parent
5a21493fb7
commit
9874f342e2
10 changed files with 212 additions and 16 deletions
|
@ -11,6 +11,8 @@
|
|||
- [Lists](concepts/lists.md)
|
||||
- [Adding Interactivity](concepts/interactivity.md)
|
||||
- [Event handlers](concepts/event_handlers.md)
|
||||
- [Hooks and Internal State](concepts/hooks.md)
|
||||
- [Fundamental Hooks and `use_hook`](concepts/usestate.md)
|
||||
- [User Input and Controlled Components](concepts/errorhandling.md)
|
||||
- [Lifecycle, updates, and effects](concepts/lifecycles.md)
|
||||
|
||||
|
@ -30,7 +32,6 @@ Extracting State Logic into a Reducer
|
|||
Passing Data Deeply with Context
|
||||
Scaling Up with Reducer and Context -->
|
||||
- [Managing State](concepts/managing_state.md)
|
||||
- [Hooks and Internal State](concepts/hooks.md)
|
||||
- [Global State](concepts/sharedstate.md)
|
||||
- [Error handling](concepts/errorhandling.md)
|
||||
- [Effects](concepts/effects.md)
|
||||
|
|
|
@ -84,7 +84,7 @@ struct PostProps {
|
|||
|
||||
And our render function:
|
||||
```rust
|
||||
fn Post((cx, props): Component<PostProps>) -> Element {
|
||||
fn Post((cx, props): Scope<PostProps>) -> Element {
|
||||
cx.render(rsx!{
|
||||
div { class: "post-container"
|
||||
VoteButton {
|
||||
|
@ -120,7 +120,7 @@ struct VoteButtonProps {
|
|||
score: i32
|
||||
}
|
||||
|
||||
fn VoteButton((cx, props): Component<VoteButtonProps>) -> Element {
|
||||
fn VoteButton((cx, props): Scope<VoteButtonProps>) -> Element {
|
||||
cx.render(rsx!{
|
||||
div { class: "votebutton"
|
||||
div { class: "arrow up" }
|
||||
|
@ -145,7 +145,7 @@ struct TitleCardProps<'a> {
|
|||
title: &'a str,
|
||||
}
|
||||
|
||||
fn TitleCard<'a>((cx, props): Component<'a, TitleCardProps>) -> Element<'a> {
|
||||
fn TitleCard<'a>((cx, props): Scope<'a, TitleCardProps>) -> Element<'a> {
|
||||
cx.render(rsx!{
|
||||
h1 { "{props.title}" }
|
||||
})
|
||||
|
@ -174,7 +174,7 @@ function Component(props) {
|
|||
Because Dioxus needs to work with the rules of Rust it uses the `Context` object to maintain some internal bookkeeping. That's what the `Context` object is: a place for the component to store state, manage listeners, and allocate elements. Advanced users of Dioxus will want to learn how to properly leverage the `Context` object to build robust and performant extensions for Dioxus.
|
||||
|
||||
```rust
|
||||
fn Post((cx /* <-- our Context object*/, props): Component<PostProps>) -> Element {
|
||||
fn Post((cx /* <-- our Context object*/, props): Scope<PostProps>) -> Element {
|
||||
cx.render(rsx!{ })
|
||||
}
|
||||
```
|
||||
|
|
|
@ -26,7 +26,7 @@ struct AppProps {
|
|||
Now that we have a "logged_in" flag accessible in our props, we can render two different screens:
|
||||
|
||||
```rust
|
||||
fn App((cx, props): Component<AppProps>) -> Element {
|
||||
fn App((cx, props): Scope<AppProps>) -> Element {
|
||||
if props.logged_in {
|
||||
cx.render(rsx!{
|
||||
DashboardScreen {}
|
||||
|
@ -48,7 +48,7 @@ Rust provides us algebraic datatypes: enums that can contain values. Using the `
|
|||
For instance, we could run a function that returns a Result:
|
||||
|
||||
```rust
|
||||
fn App((cx, props): Component<()>) -> Element {
|
||||
fn App((cx, props): Scope<()>) -> Element {
|
||||
match get_name() {
|
||||
Ok(name) => cx.render(rsx!( "Hello, {name}!" )),
|
||||
Err(err) => cx.render(rsx!( "Sorry, I don't know your name, because an error occurred: {err}" )),
|
||||
|
@ -58,7 +58,7 @@ fn App((cx, props): Component<()>) -> Element {
|
|||
|
||||
We can even match against values:
|
||||
```rust
|
||||
fn App((cx, props): Component<()>) -> Element {
|
||||
fn App((cx, props): Scope<()>) -> Element {
|
||||
match get_name() {
|
||||
"jack" => cx.render(rsx!( "Hey Jack, how's Diane?" )),
|
||||
"diane" => cx.render(rsx!( "Hey Diana, how's Jack?" )),
|
||||
|
@ -72,7 +72,7 @@ Do note: the `rsx!` macro returns a `Closure`, an anonymous function that has a
|
|||
To make patterns like these less verbose, the `rsx!` macro accepts an optional first argument on which it will call `render`. Our previous component can be shortened with this alternative syntax:
|
||||
|
||||
```rust
|
||||
fn App((cx, props): Component<()>) -> Element {
|
||||
fn App((cx, props): Scope<()>) -> Element {
|
||||
match get_name() {
|
||||
"jack" => rsx!(cx, "Hey Jack, how's Diane?" ),
|
||||
"diane" => rsx!(cx, "Hey Diana, how's Jack?" ),
|
||||
|
@ -89,7 +89,7 @@ static App: Fc<()> = |(cx, props)| rsx!(cx, "hello world!");
|
|||
Alternatively, for match statements, we can just return the builder itself and pass it into a final, single call to `cx.render`:
|
||||
|
||||
```rust
|
||||
fn App((cx, props): Component<()>) -> Element {
|
||||
fn App((cx, props): Scope<()>) -> Element {
|
||||
let greeting = match get_name() {
|
||||
"jack" => rsx!("Hey Jack, how's Diane?" ),
|
||||
"diane" => rsx!("Hey Diana, how's Jack?" ),
|
||||
|
|
|
@ -1 +1,11 @@
|
|||
# Event handlers
|
||||
|
||||
In the overview for this section, we mentioned how we can modify the state of our component by responding to user-generated events inside of event listeners.
|
||||
|
||||
In this section, we'll talk more about event listeners:
|
||||
- What events are available
|
||||
- Handling event data
|
||||
- Mutability in event listeners
|
||||
|
||||
## Event Listeners
|
||||
|
||||
|
|
|
@ -1 +1,185 @@
|
|||
# Adding Interactivity
|
||||
|
||||
So far, we've learned how to describe the structure and properties of our user interfaces. Unfortunately, they're static and quite a bit uninteresting. In this chapter, we're going to learn how to add interactivity through events, state, and tasks.
|
||||
|
||||
## Primer on interactivity
|
||||
|
||||
Before we get too deep into the mechanics of interactivity, we should first understand how Dioxus exactly chooses to handle user interaction and updates to your app.
|
||||
|
||||
### What is state?
|
||||
|
||||
Every app you'll ever build has some sort of information that needs to be rendered to the screen. Dioxus is responsible for translating your desired user interface to what is rendered to the screen. *You* are responsible for providing the content.
|
||||
|
||||
The dynamic data in your user interface is called `State`.
|
||||
|
||||
When you first launch your app with `dioxus::web::launch_with_props` you'll be providing the initial state. You need to declare the initial state *before* starting the app.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// declare our initial state
|
||||
let props = PostProps {
|
||||
id: Uuid::new_v4(),
|
||||
score: 10,
|
||||
comment_count: 0,
|
||||
post_time: std::time::Instant::now(),
|
||||
url: String::from("dioxuslabs.com"),
|
||||
title: String::from("Hello, world"),
|
||||
original_poster: String::from("dioxus")
|
||||
};
|
||||
|
||||
// start the render loop
|
||||
dioxus::desktop::launch_with_props(Post, props);
|
||||
}
|
||||
```
|
||||
|
||||
When Dioxus renders your app, it will pass an immutable reference of `PostProps` to your `Post` component. Here, you can pass the state down into children.
|
||||
|
||||
```rust
|
||||
fn App((cx, props): Scope<PostProps>) -> Element {
|
||||
cx.render(rsx!{
|
||||
Title { title: &props.title }
|
||||
Score { score: &props.score }
|
||||
// etc
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
State in Dioxus follows a pattern called "one-way-data-flow." As your components create new components as their children, your app's structure will eventually grow into a tree where state gets passed down from the root component into "leaves" of the tree.
|
||||
|
||||
You've probably seen the tree of UI components represented using an directed-acyclic-graph:
|
||||
|
||||
![image](../images/component_tree.png)
|
||||
|
||||
With Dioxus, your state will always flow down from parent components into child components.
|
||||
|
||||
### How do I change my app's state?
|
||||
|
||||
We've talked about the data flow of state, but we haven't yet talked about how to change that state dynamically. Dioxus provides a variety of ways to change the state of your app while it's running.
|
||||
|
||||
For starters, we _could_ use the `update_root_props` method on the VirtualDom to provide an entirely new root state of your App. However, for most applications, you probably don't want to regenerate your entire app just to update some text or a flag.
|
||||
|
||||
Instead, you'll want to store state internally in your components and let *that* flow down the tree. To store state in your components, you'll use something called a `hook`. Hooks are special functions that reserve a slot of state in your component's memory and provide some functionality to update that state.
|
||||
|
||||
The most common hook you'll use for storing state is `use_state`. `use_state` provides a slot for some data that allows you to read and update the value without accidentally mutating it.
|
||||
|
||||
```rust
|
||||
fn App((cx, props): Scope<()>) -> Element {
|
||||
let post = use_state(|| {
|
||||
PostData {
|
||||
id: Uuid::new_v4(),
|
||||
score: 10,
|
||||
comment_count: 0,
|
||||
post_time: std::time::Instant::now(),
|
||||
url: String::from("dioxuslabs.com"),
|
||||
title: String::from("Hello, world"),
|
||||
original_poster: String::from("dioxus")
|
||||
}
|
||||
});
|
||||
|
||||
cx.render(rsx!{
|
||||
Title { title: &post.title }
|
||||
Score { score: &post.score }
|
||||
// etc
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
Whenever we have a new post that we want to render, we can call `set` on `post` and provide a new value:
|
||||
|
||||
```rust
|
||||
post.set(PostData {
|
||||
id: Uuid::new_v4(),
|
||||
score: 20,
|
||||
comment_count: 0,
|
||||
post_time: std::time::Instant::now(),
|
||||
url: String::from("google.com"),
|
||||
title: String::from("goodbye, world"),
|
||||
original_poster: String::from("google")
|
||||
})
|
||||
```
|
||||
|
||||
We'll dive deeper into how exactly these hooks work later.
|
||||
|
||||
### When do I update my state?
|
||||
|
||||
There are a few different approaches to choosing when to update your state. You can update your state in response to user-triggered events or asynchronously in some background task.
|
||||
|
||||
### Updating state in listeners
|
||||
|
||||
When responding to user-triggered events, we'll want to "listen" for an event on some element in our component.
|
||||
|
||||
For example, let's say we provide a button to generate a new post. Whenever the user clicks the button, they get a new post. To achieve this functionality, we'll want to attach a function to the `on_click` method of `button`. Whenever the button is clicked, our function will run, and we'll get new Post data to work with.
|
||||
|
||||
```rust
|
||||
fn App((cx, props): Scope<()>) -> Element {
|
||||
let post = use_state(|| PostData::new());
|
||||
|
||||
cx.render(rsx!{
|
||||
button {
|
||||
on_click: move |_| post.set(PostData::random())
|
||||
"Generate a random post"
|
||||
}
|
||||
Post { props: &post }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
We'll dive much deeper into event listeners later.
|
||||
|
||||
### Updating state asynchronously
|
||||
|
||||
We can also update our state outside of event listeners with `tasks`. `Tasks` are asynchronous blocks of our component that have the ability to cleanly interact with values, hooks, and other data in the component. `Tasks` are one-shot - if they don't complete before the component is updated by another `.set` call, then they won't finish.
|
||||
|
||||
We can use tasks in our components to build a tiny stopwatch that ticks every second.
|
||||
|
||||
```rust
|
||||
|
||||
fn App((cx, props): Scope<()>) -> Element {
|
||||
let mut sec_elapsed = use_state(|| 0);
|
||||
|
||||
cx.spawn_task(async move {
|
||||
TimeoutFuture::from_ms(1000).await;
|
||||
sec_elapsed += 1;
|
||||
});
|
||||
|
||||
cx.render(rsx!{
|
||||
div { "Current stopwatch time: {sec_elapsed}" }
|
||||
})
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
Using asynchronous code can be difficult! This is just scratching the surface of what's possible. We have an entire chapter on using async properly in your Dioxus Apps.
|
||||
|
||||
### How do I tell Dioxus that my state changed?
|
||||
|
||||
So far, we've only updated our state with `.set`. However, you might've noticed that we used `AddAssign` to increment the `sec_elapsed` value in our stopwatch example *without* calling set. This is because the `AddAssign` trait is implemented for `UseState<T>` (the wrapper around our value returned from `use_state`). Under the hood, whenever you try to mutate our value through `UseState`, you're actually calling `.set` which informs Dioxus that _this_ component needs to be updated on the screen.
|
||||
|
||||
Whenever you inform Dioxus that the component needs to be updated, it will "render" your component again, storing the previous and current Elements in memory. Dioxus will automatically figure out the differences between the old and the new and generate a list of edits that the renderer needs to apply to change what's on the screen. This process is called "diffing":
|
||||
|
||||
![Diffing](../images/diffing.png)
|
||||
|
||||
In React, the specifics of when a component gets re-rendered is somewhat blurry. With Dioxus, any component can mark itself as "dirty" through a method on `Context`: `needs_update`. In addition, any component can mark any _other_ component as dirty provided it knows the other component's ID with `needs_update_any`.
|
||||
|
||||
With these building blocks, we can craft new hooks similar to `use_state` that let us easily tell Dioxus that new information is ready to be sent to the screen.
|
||||
|
||||
### How do I update my state efficiently?
|
||||
|
||||
In general, Dioxus should be plenty fast for most use cases. However, there are some rules you should consider following to ensure your apps are quick.
|
||||
|
||||
- 1) **Don't call set—state _while rendering_**. This will cause Dioxus to unnecessarily re-check the component for updates.
|
||||
- 2) **Break your state apart into smaller sections.** Hooks are explicitly designed to "unshackle" your state from the typical model-view-controller paradigm, making it easy to reuse useful bits of code with a single function.
|
||||
- 3) **Move local state down**. Dioxus will need to re-check child components of your app if the root component is constantly being updated. You'll get best results if rapidly-changing state does not cause major re-renders.
|
||||
|
||||
Don't worry - Dioxus is fast. But, if your app needs *extreme performance*, then take a look at the `Performance Tuning` in the `Advanced Guides` book.
|
||||
|
||||
|
||||
|
||||
## Moving On
|
||||
|
||||
This overview was a lot of information - but it doesn't tell you everything!
|
||||
|
||||
In the next sections we'll go over:
|
||||
- `use_state` in depth
|
||||
- `use_ref` and other hooks
|
||||
- Handling user input
|
||||
|
|
1
docs/guide/src/concepts/usestate.md
Normal file
1
docs/guide/src/concepts/usestate.md
Normal file
|
@ -0,0 +1 @@
|
|||
# Fundamental Hooks and use_hook
|
|
@ -129,7 +129,7 @@ rsx!(
|
|||
)
|
||||
```
|
||||
|
||||
Note: the name of the custom attribute must match exactly what you want the renderer to output. All attributes defined as methods in `dioxus-html` follow the snake_case naming convention. However, they internally translate their snake_case convention to HTML's camelCase convention.
|
||||
Note: the name of the custom attribute must match exactly what you want the renderer to output. All attributes defined as methods in `dioxus-html` follow the snake_case naming convention. However, they internally translate their snake_case convention to HTML's camelCase convention. When using custom attributes, make sure the name of the attribute exactly matches what the renderer is expecting.
|
||||
|
||||
## Listeners
|
||||
|
||||
|
|
BIN
docs/guide/src/images/component_tree.png
Normal file
BIN
docs/guide/src/images/component_tree.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 3.6 KiB |
BIN
docs/guide/src/images/diffing.png
Normal file
BIN
docs/guide/src/images/diffing.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 23 KiB |
|
@ -65,6 +65,10 @@ impl<'src> Context<'src> {
|
|||
(self.scope.memoized_updater)()
|
||||
}
|
||||
|
||||
pub fn needs_update_any(&self, id: ScopeId) {
|
||||
(self.scope.shared.schedule_any_immediate)(id)
|
||||
}
|
||||
|
||||
/// Schedule an update for any component given its ScopeId.
|
||||
///
|
||||
/// A component's ScopeId can be obtained from `use_hook` or the [`Context::scope_id`] method.
|
||||
|
@ -101,11 +105,7 @@ impl<'src> Context<'src> {
|
|||
/// cx.render(lazy_tree)
|
||||
/// }
|
||||
///```
|
||||
pub fn render(
|
||||
self,
|
||||
lazy_nodes: Option<LazyNodes<'src, '_>>,
|
||||
// lazy_nodes: Option<Box<dyn FnOnce(NodeFactory<'src>) -> VNode<'src> + '_>>,
|
||||
) -> Option<VNode<'src>> {
|
||||
pub fn render(self, lazy_nodes: Option<LazyNodes<'src, '_>>) -> Option<VNode<'src>> {
|
||||
let bump = &self.scope.frames.wip_frame().bump;
|
||||
let factory = NodeFactory { bump };
|
||||
lazy_nodes.map(|f| f.call(factory))
|
||||
|
|
Loading…
Reference in a new issue