In Yew, passing functions as props is a common pattern for implementing communication between components. This typically occurs when you want the child component to trigger certain functions or behaviors in the parent component. Below are the specific steps and examples for implementing this in Yew:
1. Define a Props Struct
First, define a Props struct in the child component that includes a function. This function is typically a callback defined in the parent component and passed to the child component.
rustuse yew::prelude::*; #[derive(Properties, PartialEq)] pub struct ChildProps { pub on_click: Callback<()>, }
Here, Callback is a type provided by Yew that encapsulates a callable callback. Callback<()> indicates that this callback does not take parameters and does not return a value.
2. Use the Function in the Child Component
In the implementation of the child component, you can use the passed-in function. This is typically triggered in response to user interactions, such as clicking a button.
rustpub struct Child; impl Component for Child { type Message = (); type Properties = ChildProps; fn create(ctx: &Context<Self>) -> Self { Self } fn view(&self, ctx: &Context<Self>) -> Html { html! { <button {onclick: ctx.props().on_click.reform(|_| ())}> { "Click me!" } </button> } } }
In the above example, we create a button and set its onclick event handler. When the button is clicked, the passed callback function is invoked.
3. Pass the Function in the Parent Component
Finally, in the parent component, you need to pass a specific callback function to the child component.
rustpub struct Parent; impl Component for Parent { type Message = (); type Properties = (); fn create(ctx: &Context<Self>) -> Self { Self } fn view(&self, ctx: &Context<Self>) -> Html { let on_click = ctx.link().callback(|_| { log::info!("Button clicked in child component!"); }); html! { <Child {on_click} /> } } }
Here, we use ctx.link().callback to create a callback that executes the specified code when triggered (in this example, logging a message).
Summary
In this way, Yew allows the parent component to pass callback functions to the child component via props, enabling the child component to invoke functions defined in the parent component at the appropriate time. This is a powerful pattern that helps you build complex interactive interfaces while maintaining decoupling between components.