rust 如何在紫杉中传递函数作为道具?

iaqfqrcu  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(227)

我只是想通过我的一个孩子的道具传递一个函数,这样它就可以在那里使用。

这是我现在拥有的代码

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>();
}

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

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)

我可以实现IntoPropValue特征,但是仅仅将一个函数传递给child似乎有点多余,有没有更简单的方法来实现?

bksxznpy

bksxznpy1#

一个简单的解决方案是使用yew的Callback。下面是如何使用上面的示例来实现它。
该代码执行的一些操作与上面的代码不同
1.它会做use yew::Callback
1.它将MyProps中的fn(Event) -> ()更改为Callback<Event>
1.它通过执行Callback::from(do_this_func)来创建Callback
1.为了调用传递的实际函数,它使用emit,即do_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>();
}

相关问题