Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs-src/0.3/en/async/use_future.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# UseFuture

[`use_future`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_future.html) lets you run an async closure, and provides you with its result.
[`use_future`](https://docs.rs/dioxus-hooks/~0.3/dioxus_hooks/fn.use_future.html) lets you run an async closure, and provides you with its result.

For example, we can make an API request (using [reqwest](https://docs.rs/reqwest/latest/reqwest/index.html)) inside `use_future`:

Expand Down
2 changes: 1 addition & 1 deletion docs-src/0.3/en/custom_renderer/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ For reference, check out the [javascript interpreter](https://github.com/DioxusL

## Templates

Dioxus is built around the concept of [Templates](https://docs.rs/dioxus-core/latest/dioxus_core/prelude/struct.Template.html). Templates describe a UI tree known at compile time with dynamic parts filled at runtime. This is useful internally to make skip diffing static nodes, but it is also useful for the renderer to reuse parts of the UI tree. This can be useful for things like a list of items. Each item could contain some static parts and some dynamic parts. The renderer can use the template to create a static part of the UI once, clone it for each element in the list, and then fill in the dynamic parts.
Dioxus is built around the concept of [Templates](https://docs.rs/dioxus-core/~0.3/dioxus_core/struct.Template.html). Templates describe a UI tree known at compile time with dynamic parts filled at runtime. This is useful internally to make skip diffing static nodes, but it is also useful for the renderer to reuse parts of the UI tree. This can be useful for things like a list of items. Each item could contain some static parts and some dynamic parts. The renderer can use the template to create a static part of the UI once, clone it for each element in the list, and then fill in the dynamic parts.

## Mutations

Expand Down
2 changes: 1 addition & 1 deletion docs-src/0.3/en/describing_ui/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ You can render multiple elements at the top level of `rsx!` and they will be aut

### Expressions

You can include arbitrary Rust expressions as children within RSX that implements [IntoDynNode](https://docs.rs/dioxus-core/0.3/dioxus_core/trait.IntoDynNode.html). This is useful for displaying data from an [iterator](https://doc.rust-lang.org/stable/book/ch13-02-iterators.html#processing-a-series-of-items-with-iterators):
You can include arbitrary Rust expressions as children within RSX that implements [IntoDynNode](https://docs.rs/dioxus-core/~0.3/dioxus_core/trait.IntoDynNode.html). This is useful for displaying data from an [iterator](https://doc.rust-lang.org/stable/book/ch13-02-iterators.html#processing-a-series-of-items-with-iterators):

```rust
{{#include ../docs-router/src/doc_examples/untested_03/rsx_overview.rs:expression}}
Expand Down
6 changes: 3 additions & 3 deletions docs-src/0.3/en/interactivity/custom_hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ For example, if many components need to access an `AppSettings` struct, you can

## Custom Hook Logic

You can use [`cx.use_hook`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.Scope.html#method.use_hook) to build your own hooks. In fact, this is what all the standard hooks are built on!
You can use [`cx.use_hook`](https://docs.rs/dioxus/~0.3/dioxus/prelude/struct.ScopeState.html#method.use_hook) to build your own hooks. In fact, this is what all the standard hooks are built on!

`use_hook` accepts a single closure for initializing the hook. It will be only run the first time the component is rendered. The return value of that closure will be used as the value of the hook – Dioxus will take it, and store it for as long as the component is alive. On every render (not just the first one!), you will get a reference to this value.

> Note: You can implement [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html) for your hook value – it will be dropped then the component is unmounted (no longer in the UI)

Inside the initialization closure, you will typically make calls to other `cx` methods. For example:

- The `use_state` hook tracks state in the hook value, and uses [`cx.schedule_update`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.Scope.html#method.schedule_update) to make Dioxus re-render the component whenever it changes.
- The `use_context` hook calls [`cx.consume_context`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.Scope.html#method.consume_context) (which would be expensive to call on every render) to get some context from the scope
- The `use_state` hook tracks state in the hook value, and uses [`cx.schedule_update`](https://docs.rs/dioxus/~0.3/dioxus/prelude/struct.ScopeState.html#method.schedule_update) to make Dioxus re-render the component whenever it changes.
- The `use_context` hook calls [`cx.consume_context`](https://docs.rs/dioxus/~0.3/dioxus/prelude/struct.ScopeState.html#method.consume_context) (which would be expensive to call on every render) to get some context from the scope
4 changes: 2 additions & 2 deletions docs-src/0.3/en/interactivity/event_handlers.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ For example, to handle clicks on an element, we can specify an `onclick` handler

## The Event object

Event handlers receive an [`Event`](https://docs.rs/dioxus-core/latest/dioxus_core/struct.Event.html) object containing information about the event. Different types of events contain different types of data. For example, mouse-related events contain [`MouseData`](https://docs.rs/dioxus/latest/dioxus/events/struct.MouseData.html), which tells you things like where the mouse was clicked and what mouse buttons were used.
Event handlers receive an [`Event`](https://docs.rs/dioxus-core/~0.3/dioxus_core/struct.Event.html) object containing information about the event. Different types of events contain different types of data. For example, mouse-related events contain [`MouseData`](https://docs.rs/dioxus/~0.3/dioxus/events/struct.MouseData.html), which tells you things like where the mouse was clicked and what mouse buttons were used.

In the example above, this event data was logged to the terminal:

Expand All @@ -23,7 +23,7 @@ Clicked! Event: UiEvent { bubble_state: Cell { value: true }, data: MouseData {
Clicked! Event: UiEvent { bubble_state: Cell { value: true }, data: MouseData { coordinates: Coordinates { screen: (242.0, 256.0), client: (26.0, 17.0), element: (16.0, 7.0), page: (26.0, 17.0) }, modifiers: (empty), held_buttons: EnumSet(), trigger_button: Some(Primary) } }
```

To learn what the different event types for HTML provide, read the [events module docs](https://docs.rs/dioxus-html/latest/dioxus_html/events/index.html).
To learn what the different event types for HTML provide, read the [events module docs](https://docs.rs/dioxus-html/~0.3/dioxus_html/events/index.html).

### Event propagation

Expand Down
6 changes: 3 additions & 3 deletions docs-src/0.3/en/interactivity/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Hooks allow us to create state in our components. Hooks are Rust functions that

## use_state Hook

[`use_state`](https://docs.rs/dioxus/latest/dioxus/prelude/fn.use_state.html) is one of the simplest hooks.
[`use_state`](https://docs.rs/dioxus/~0.3/dioxus/prelude/fn.use_state.html) is one of the simplest hooks.

- You provide a closure that determines the initial value
- `use_state` gives you the current value, and a way to update it by setting it to something else
Expand All @@ -21,7 +21,7 @@ For example, you might have seen the counter example, in which state (a number)

Every time the component's state changes, it re-renders, and the component function is called, so you can describe what you want the new UI to look like. You don't have to worry about "changing" anything – just describe what you want in terms of the state, and Dioxus will take care of the rest!

> `use_state` returns your value wrapped in a smart pointer of type [`UseState`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.UseState.html). This is why you can both read the value and update it, even within an event handler.
> `use_state` returns your value wrapped in a smart pointer of type [`UseState`](https://docs.rs/dioxus/~0.3/dioxus/prelude/struct.UseState.html). This is why you can both read the value and update it, even within an event handler.

You can use multiple hooks in the same component if you want:

Expand Down Expand Up @@ -67,7 +67,7 @@ These rules mean that there are certain things you can't do with hooks:

## use_ref Hook

`use_state` is great for tracking simple values. However, you may notice in the [`UseState` API](https://docs.rs/dioxus/latest/dioxus/hooks/struct.UseState.html) that the only way to modify its value is to replace it with something else (e.g., by calling `set`, or through one of the `+=`, `-=` operators). This works well when it is cheap to construct a value (such as any primitive). But what if you want to maintain more complex data in the components state?
`use_state` is great for tracking simple values. However, you may notice in the [`UseState` API](https://docs.rs/dioxus/~0.3/dioxus/prelude/struct.UseState.html) that the only way to modify its value is to replace it with something else (e.g., by calling `set`, or through one of the `+=`, `-=` operators). This works well when it is cheap to construct a value (such as any primitive). But what if you want to maintain more complex data in the components state?

For example, suppose we want to maintain a `Vec` of values. If we stored it with `use_state`, the only way to add a new value to the list would be to create a new `Vec` with the additional value, and put it in the state. This is expensive! We want to modify the existing `Vec` instead.

Expand Down
2 changes: 1 addition & 1 deletion docs-src/0.3/en/interactivity/sharing_state.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Suppose now that we want to implement a dark mode toggle for our app. To achieve

Now, we could write another `use_state` in the top component, and pass `is_dark_mode` down to every component through props. But think about what will happen as the app grows in complexity – almost every component that renders any CSS is going to need to know if dark mode is enabled or not – so they'll all need the same dark mode prop. And every parent component will need to pass it down to them. Imagine how messy and verbose that would get, especially if we had components several levels deep!

Dioxus offers a better solution than this "prop drilling" – providing context. The [`use_context_provider`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context_provider.html) hook is similar to `use_ref`, but it makes it available through [`use_context`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context.html) for all children components.
Dioxus offers a better solution than this "prop drilling" – providing context. The [`use_context_provider`](https://docs.rs/dioxus-hooks/~0.3/dioxus_hooks/fn.use_context_provider.html) hook is similar to `use_ref`, but it makes it available through [`use_context`](https://docs.rs/dioxus-hooks/~0.3/dioxus_hooks/fn.use_context.html) for all children components.

First, we have to create a struct for our dark mode configuration:

Expand Down
2 changes: 1 addition & 1 deletion docs-src/0.3/pt-br/async/use_future.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# UseFuture

[`use_future`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_future.html) permite executar um encerramento assíncrono e fornece seu resultado.
[`use_future`](https://docs.rs/dioxus-hooks/~0.3/dioxus_hooks/fn.use_future.html) permite executar um encerramento assíncrono e fornece seu resultado.

Por exemplo, podemos fazer uma solicitação de API dentro de `use_future`:

Expand Down
6 changes: 3 additions & 3 deletions docs-src/0.3/pt-br/interactivity/custom_hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ Por exemplo, se muitos componentes precisam acessar uma _struct_ `AppSettings`,

## Lógica de Hook Personalizada

Você pode usar [`cx.use_hook`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.Scope.html#method.use_hook) para construir seus próprios _hooks_. Na verdade, é nisso que todos os _hooks_ padrão são construídos!
Você pode usar [`cx.use_hook`](https://docs.rs/dioxus/~0.3/dioxus/prelude/struct.ScopeState.html#method.use_hook) para construir seus próprios _hooks_. Na verdade, é nisso que todos os _hooks_ padrão são construídos!

`use_hook` aceita um único encerramento para inicializar o _hook_. Ele será executado apenas na primeira vez que o componente for renderizado. O valor de retorno desse encerramento será usado como o valor do _hook_ – o Dioxus o pegará e o armazenará enquanto o componente estiver vivo. Em cada renderização (não apenas na primeira!), você receberá uma referência a esse valor.

> Nota: Você pode implementar [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html) para o valor do seu _hook_ – ele será descartado e o componente será desmontado (não mais na interface do usuário)

Dentro do encerramento de inicialização, você normalmente fará chamadas para outros métodos `cx`. Por exemplo:

- O _hook_ `use_state` rastreia o estado no valor do _hook_ e usa [`cx.schedule_update`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.Scope.html#method.schedule_update) para o Dioxus renderizar novamente o componente sempre que ele for alterado.
- O _hook_ `use_context` chama [`cx.consume_context`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.Scope.html#method.consume_context) (que seria custoso chamar em cada render) para obter algum contexto do escopo
- O _hook_ `use_state` rastreia o estado no valor do _hook_ e usa [`cx.schedule_update`](https://docs.rs/dioxus/~0.3/dioxus/prelude/struct.ScopeState.html#method.schedule_update) para o Dioxus renderizar novamente o componente sempre que ele for alterado.
- O _hook_ `use_context` chama [`cx.consume_context`](https://docs.rs/dioxus/~0.3/dioxus/prelude/struct.ScopeState.html#method.consume_context) (que seria custoso chamar em cada render) para obter algum contexto do escopo
4 changes: 2 additions & 2 deletions docs-src/0.3/pt-br/interactivity/event_handlers.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Por exemplo, para manipular cliques em um elemento, podemos especificar um manip

## O Objeto `Evento`

Os manipuladores de eventos recebem um objeto [`UiEvent`](https://docs.rs/dioxus-core/latest/dioxus_core/struct.UiEvent.html) contendo informações sobre o evento. Diferentes tipos de eventos contêm diferentes tipos de dados. Por exemplo, eventos relacionados ao mouse contêm [`MouseData`](https://docs.rs/dioxus/latest/dioxus/events/struct.MouseData.html), que informa coisas como onde o mouse foi clicado e quais botões do mouse foram usados.
Os manipuladores de eventos recebem um objeto [`Event`](https://docs.rs/dioxus-core/~0.3/dioxus_core/struct.Event.html) contendo informações sobre o evento. Diferentes tipos de eventos contêm diferentes tipos de dados. Por exemplo, eventos relacionados ao mouse contêm [`MouseData`](https://docs.rs/dioxus/~0.3/dioxus/events/struct.MouseData.html), que informa coisas como onde o mouse foi clicado e quais botões do mouse foram usados.

No exemplo acima, esses dados de evento foram registrados no terminal:

Expand All @@ -23,7 +23,7 @@ Clicked! Event: UiEvent { data: MouseData { coordinates: Coordinates { screen: (
Clicked! Event: UiEvent { data: MouseData { coordinates: Coordinates { screen: (468.0, 109.0), client: (73.0, 25.0), element: (63.0, 15.0), page: (73.0, 25.0) }, modifiers: (empty), held_buttons: EnumSet(), trigger_button: Some(Primary) } }
```

Para saber o que os diferentes tipos de eventos fornecem, leia os [documentos do módulo de eventos](https://docs.rs/dioxus/latest/dioxus/events/index.html).
Para saber o que os diferentes tipos de eventos fornecem, leia os [documentos do módulo de eventos](https://docs.rs/dioxus/~0.3/dioxus/events/index.html).

### Parando a propagação

Expand Down
6 changes: 3 additions & 3 deletions docs-src/0.3/pt-br/interactivity/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Para lógica com estado, você pode usar _hooks_. _Hooks_ são funções Rust qu

## Hook `use_state`

[`use_state`](https://docs.rs/dioxus/latest/dioxus/hooks/fn.use_state.html) é um dos _hooks_ mais simples.
[`use_state`](https://docs.rs/dioxus/~0.3/dioxus/prelude/fn.use_state.html) é um dos _hooks_ mais simples.

- Você fornece um fechamento que determina o valor inicial
- `use_state` fornece o valor atual e uma maneira de atualizá-lo, definindo-o para outra coisa
Expand All @@ -22,7 +22,7 @@ Por exemplo, você pode ter visto o exemplo do contador, no qual o estado (um n

Toda vez que o estado do componente muda, ele é renderizado novamente e a função do componente é chamada, para que você possa descrever como deseja que a nova interface do usuário se pareça. Você não precisa se preocupar em "mudar" nada - apenas descreva o que você quer em termos de estado, e Dioxus cuidará do resto!

> `use_state` retorna seu valor envolto em uma _smart pointer_ do tipo [`UseState`](https://docs.rs/dioxus/latest/dioxus/hooks/struct.UseState.html). É por isso que você pode ler o valor e atualizá-lo, mesmo dentro de um manipulador.
> `use_state` retorna seu valor envolto em uma _smart pointer_ do tipo [`UseState`](https://docs.rs/dioxus/~0.3/dioxus/prelude/struct.UseState.html). É por isso que você pode ler o valor e atualizá-lo, mesmo dentro de um manipulador.

Você pode usar vários _hooks_ no mesmo componente se quiser:

Expand Down Expand Up @@ -72,7 +72,7 @@ Essas regras significam que há certas coisas que você não pode fazer com _hoo

## Gancho `use_ref`

`use_state` é ótimo para rastrear valores simples. No entanto, você pode notar na [`UseState` API](https://docs.rs/dioxus/latest/dioxus/hooks/struct.UseState.html) que a única maneira de modificar seu valor é substituí-lo por algo else (por exemplo, chamando `set`, ou através de um dos operadores `+=`, `-=`). Isso funciona bem quando é barato construir um valor (como qualquer primitivo). Mas e se você quiser manter dados mais complexos no estado dos componentes?
`use_state` é ótimo para rastrear valores simples. No entanto, você pode notar na [`UseState` API](https://docs.rs/dioxus/~0.3/dioxus/prelude/struct.UseState.html) que a única maneira de modificar seu valor é substituí-lo por algo else (por exemplo, chamando `set`, ou através de um dos operadores `+=`, `-=`). Isso funciona bem quando é barato construir um valor (como qualquer primitivo). Mas e se você quiser manter dados mais complexos no estado dos componentes?

Por exemplo, suponha que queremos manter um `Vec` de valores. Se o armazenamos com `use_state`, a única maneira de adicionar um novo valor à lista seria criar um novo `Vec` com o valor adicional e colocá-lo no estado. Isto é custoso! Queremos modificar o `Vec` existente.

Expand Down
2 changes: 1 addition & 1 deletion docs-src/0.3/pt-br/interactivity/sharing_state.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Suponha agora que queremos implementar uma alternância de modo escuro para noss

Agora, poderíamos escrever outro `use_state` no componente superior e passar `is_dark_mode` para cada componente através de _props_. Mas pense no que acontecerá à medida que o aplicativo crescer em complexidade – quase todos os componentes que renderizam qualquer CSS precisarão saber se o modo escuro está ativado ou não – para que todos precisem do mesmo suporte do modo escuro. E cada componente pai precisará passá-lo para eles. Imagine como isso ficaria confuso e verboso, especialmente se tivéssemos componentes com vários níveis de profundidade!

A Dioxus oferece uma solução melhor do que esta "perfuração com hélice" – fornecendo contexto. O _hook_ [`use_context_provider`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context_provider.html) é semelhante ao `use_ref`, mas o torna disponível através do [`use_context`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context.html) para todos os componentes filhos.
A Dioxus oferece uma solução melhor do que esta "perfuração com hélice" – fornecendo contexto. O _hook_ [`use_context_provider`](https://docs.rs/dioxus-hooks/~0.3/dioxus_hooks/fn.use_context_provider.html) é semelhante ao `use_ref`, mas o torna disponível através do [`use_context`](https://docs.rs/dioxus-hooks/~0.3/dioxus_hooks/fn.use_context.html) para todos os componentes filhos.

Primeiro, temos que criar um _struct_ para nossa configuração de modo escuro:

Expand Down
Loading