我在use_effect
中有一个事件侦听器,在那里我想从鼠标事件中获取值并将其设置为状态.要添加我使用的use_node_ref
事件侦听器,但我收到下一个错误:
error[E0597]: `coordinates` does not live long enough
--> src/test.rs:33:17
|
24 | |div_ref| {
| --------- value captured here
...
29 | let listener = Closure::<dyn Fn(MouseEvent)>::wrap(Box::new(|event| {
| ________________________________________________________________-
30 | | let x = event.x();
31 | | let y = event.y();
32 | | web_sys::console::log_1(&x.into());
33 | | coordinates.set(Coordinates { x: x, y: y });
| | ^^^^^^^^^^^ borrowed value does not live long enough
34 | |
35 | | }));
| |______________- cast requires that `coordinates` is borrowed for `'static`
...
53 | }
| - `coordinates` dropped here while still borrowed
这是一个可重复使用的例子:
use wasm_bindgen::prelude::Closure;
use web_sys::HtmlElement;
use yew::prelude::*;
use wasm_bindgen::JsCast;
use web_sys;
use yew::{function_component, html, use_effect_with_deps, use_node_ref, Html};
struct Coordinates {
x: i32,
y: i32,
}
#[function_component]
fn Test() -> Html {
let div_ref = use_node_ref();
let coordinates: UseStateHandle<Coordinates> = use_state(|| Coordinates { x: 0, y: 0 });
{
let div_ref = div_ref.clone();
let coordinates = coordinates.clone();
use_effect_with_deps(
|div_ref| {
let div = div_ref
.cast::<HtmlElement>()
.expect("div_ref not attached to div element");
let listener = Closure::<dyn Fn(MouseEvent)>::wrap(Box::new(|event| {
let x = event.x();
let y = event.y();
web_sys::console::log_1(&x.into());
coordinates.set(Coordinates { x: x, y: y }); // <- here is the problem
}));
div.add_event_listener_with_callback(
"mousemove",
listener.as_ref().unchecked_ref(),
)
.unwrap();
move || {
div.remove_event_listener_with_callback(
"mousemove",
listener.as_ref().unchecked_ref(),
)
.unwrap();
}
},
div_ref,
);
}
html! {
<div ref={div_ref}>{"Test"}</div>
}
}
fn main() {
yew::Renderer::<Test>::new().render();
}
如何在USE_EFECT_WITH_DEPS中设置监听器内部的状态?