有什么方法可以将 Callback<MouseEvent> 转换为 FnMut(MouseEvent) 吗?

问题描述 投票:0回答:0

我正在使用 web_sys 从头开始实现材料 3,并为其中的不同框架编写一些适配器 yew

我已经实现了按钮的基本结构like this来使用like this

这在 web_sys 上工作正常,但我正在尝试编写 yew 适配器,并且在

yew::Callback<web_sys::MouseEvent>
FnMut(web_sys::MouseEvent)
之间进行转换时遇到问题。

我的适配器看起来像这样:

use core::components::buttons::elevated::{self, ElevatedButtonData, ElevatedButtonOpts};
use web_sys::{HtmlElement, MouseEvent};
use yew::{function_component, virtual_dom::VNode, AttrValue, Callback, Html, Properties};

#[derive(PartialEq, Properties)]
pub struct ElevatedButtonProps {
    pub label: AttrValue,

    #[prop_or(false)]
    pub disable: bool,

    #[prop_or_default]
    pub icon: Option<AttrValue>,

    #[prop_or_default]
    pub onclick: Option<Callback<MouseEvent>>,
}

#[function_component(ElevatedButton)]
pub fn elevated_button(props: &ElevatedButtonProps) -> Html {
    let ElevatedButtonProps {
        label,
        disable,
        icon,
        onclick,
    } = props;

    let icon = if let Some(icon) = icon {
        Some(icon.to_string())
    } else {
        None
    };

    let inner = if let Some(onclick) = onclick {
        // problem is here when i'm trying to cast
        let cb = move |e: MouseEvent| {
            onclick.clone().emit(e.clone());
        };

        ElevatedButtonData {
            label: label.to_string(),
            icon,
            onclick: Some(Box::new(cb.clone())),
        }
    } else {
        ElevatedButtonData {
            label: label.to_string(),
            icon,
            onclick: None,
        }
    };

    let opts = ElevatedButtonOpts { disable: *disable };

    let button: HtmlElement = elevated::ElevatedButton::new(inner, opts);

    VNode::VRef(button.into())
}

但这不起作用...

编译器告诉我

yew::Callback
必须比
'static
更长寿,但同时宏注释
function_component
不允许我使用生命周期注释。

20 | pub fn elevated_button(props: &ElevatedButtonProps) -> Html {
   |                               - let's call the lifetime of this reference `'1`
...
42 |             onclick: Some(Box::new(cb.clone())),
   |                           ^^^^^^^^^^^^^^^^^^^^ cast requires that `'1` must outlive `'static`

有人知道我该如何处理这个问题吗?

rust lifetime yew web-sys
© www.soinside.com 2019 - 2024. All rights reserved.