如何在 Yew 中将函数作为 Prop 传递?

sc3*_*000 4 rust yew

我只是想通过我的一个孩子的 props 将一个函数传递给他们,以便在那里使用它。

这是我现在的代码

use log::info;
use yew::html::onclick::Event;
use yew::prelude::*;


// Create Properties with the function I want to use
#[derive(yew::Properties, PartialEq)]
pub struct MyProps {
    pub do_this: fn(Event) -> (),
    pub val: String,
}

#[function_component(Base)]
pub fn home(props: &MyProps) -> Html {
    let do_this_func = props.do_this.clone();
    html! {
        <button onclick={move |e: Event|  do_this_func(e)}>  {"press me"} </button>
    }
}

// Pass the function
#[function_component(App)]
pub fn app() -> Html {
    fn do_this_func(s: Event) {
        info!("clicked from my func")
    }
    html! {
        <Base do_this={do_this_func} val={"hello".to_string()} />
    }
}

fn main() {
    wasm_logger::init(wasm_logger::Config::default());
    yew::start_app::<App>();
}

Run Code Online (Sandbox Code Playgroud)

如果我删除do_this并传入val编译器,错误就会消失。我希望只指定道具上的类型就足够了,但事实并非如此。

这是我得到的编译器错误。

   Compiling yew-app v0.1.0 (/Users/sasacocic/development/tinkering/yew-app)
error[E0277]: the trait bound `fn(MouseEvent) {do_this_func}: IntoPropValue<fn(MouseEvent)>` is not satisfied
  --> src/main.rs:25:24
   |
25 |         <Base do_this={do_this_func} val={"hello".to_string()} />
   |               -------  ^^^^^^^^^^^^ the trait `IntoPropValue<fn(MouseEvent)>` is not implemented for `fn(MouseEvent) {do_this_func}`
   |               |
   |               required by a bound introduced by this call
   |
   = help: the following other types implement trait `IntoPropValue<T>`:
             <&'static str as IntoPropValue<AttrValue>>
             <&'static str as IntoPropValue<Classes>>
             <&'static str as IntoPropValue<Option<AttrValue>>>
             <&'static str as IntoPropValue<Option<String>>>
             <&'static str as IntoPropValue<String>>
             <&T as IntoPropValue<Option<T>>>
             <&T as IntoPropValue<T>>
             <Classes as IntoPropValue<AttrValue>>
           and 6 others
note: required by a bound in `MyPropsBuilder::<MyPropsBuilderStep_missing_required_prop_do_this>::do_this`
  --> src/main.rs:5:10
   |
5  | #[derive(yew::Properties, PartialEq)]
   |          ^^^^^^^^^^^^^^^ required by this bound in `MyPropsBuilder::<MyPropsBuilderStep_missing_required_prop_do_this>::do_this`
6  | pub struct MyProps {
7  |     pub do_this: fn(Event) -> (),
   |         ------- required by a bound in this
   = note: this error originates in the derive macro `yew::Properties` (in Nightly builds, run with -Z macro-backtrace for more info)
Run Code Online (Sandbox Code Playgroud)

我可以实现该IntoPropValue特征,但这对于仅将函数传递给子函数来说似乎有点额外。有没有更简单的方法来做到这一点?

sc3*_*000 7

一个简单的解决方案是使用 yew 的Callback. 下面介绍了如何使用上面的示例来完成此操作。

该代码做了一些与上面不同的事情

  1. 确实如此use yew::Callback
  2. fn(Event) -> ()变成MyPropsCallback<Event>
  3. Callback它通过做创造Callback::from(do_this_func)
  4. 调用传递的实际函数使用emitiedo_this_func.emit(e)

完整的代码如下并评论

use log::info;
use yew::html::onclick::Event;
use yew::prelude::*;
use yew::Callback; // import Callback

#[derive(yew::Properties, PartialEq)]
pub struct MyProps {
    pub do_this: Callback<Event>, // change fn(Event) -> () to Callback<Event>
    pub val: String,
}

#[function_component(Base)]
pub fn home(props: &MyProps) -> Html {
    let do_this_func = props.do_this.clone();

    html! {
        // calls the emit method on the Callback 
        <button onclick={move |e: Event|  do_this_func.emit(e)}>  {"press me"} </button>
    }
}

#[function_component(App)]
pub fn app() -> Html {
    fn do_this_func(s: Event) {
        info!("clicked from my func")
    }


    // creates the callback with Callback::from
    let cb = Callback::from(do_this_func);
    html! {
        <Base do_this={cb} val={"hello".to_string()} />
    }
}

fn main() {
    wasm_logger::init(wasm_logger::Config::default());
    yew::start_app::<App>();
}
Run Code Online (Sandbox Code Playgroud)