yew/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/function-components/callbacks.mdx

74 lines
2.5 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 'コールバック (Callbacks)'
---
コールバック関数は、コンポーネントツリー内で情報を上向きに伝達したり、イベント処理中に他のコンポーネント例えばエージェントやDOMと通信したりするために使用されます。内部的には、コールバック関数の型は単なる `Fn` であり、安価にクローンできるように `Rc` に包まれています。
コールバック関数を手動で呼び出したい場合は、`emit` 関数を使用できます。
```rust
use yew::{html, Component, Context, Html, Callback};
let cb: Callback<String, String> = Callback::from(move |name: String| {
format!("Bye {}", name)
});
let result = cb.emit(String::from("Bob")); // コールバック関数を呼び出す
// web_sys::console::log_1(&result.into()); // コメントを解除すると、「Bye Bob」 が出力されます
```
## コールバック関数をプロパティとして渡す
yew で一般的なパターンは、コールバック関数を作成し、それをプロパティとして子コンポーネントに渡すことです。
```rust
use yew::{function_component, html, Html, Properties, Callback};
#[derive(Properties, PartialEq)]
pub struct Props {
pub on_name_entry: Callback<String>,
}
#[function_component]
fn HelloWorld(props: &Props) -> Html {
props.on_name_entry.emit(String::from("Bob"));
html! { "Hello" }
}
// 次にプロパティ (Props) を提供します
#[function_component]
fn App() -> Html {
let on_name_entry: Callback<String> = Callback::from(move |name: String| {
let greeting = format!("Hey, {}!", name);
// web_sys::console::log_1(&greeting.into()); // コメントを解除すると、ここにテキストが出力されます
});
html! { <HelloWorld {on_name_entry} /> }
}
```
## DOM イベントとコールバック関数
コールバック関数は、DOM イベントに接続するためにも使用されます。
例えば、ここではユーザーがボタンをクリックしたときに呼び出されるコールバック関数を定義します:
```rust
use yew::{function_component, html, Html, Properties, Callback};
#[function_component]
fn App() -> Html {
let onclick = Callback::from(move |_| {
let greeting = String::from("Hi there");
// web_sys::console::log_1(&greeting.into()); // コメントを解除すると、ここにテキストが出力されます
});
html! {
<button {onclick}>{ "Click" }</button>
}
}
```