我目前正在尝试dioxus对于 Rust,我正在尝试找出如何处理全局键盘按下事件。
我想使用箭头键来回移动图像:
这是我到目前为止的代码:
use dioxus::{events::*, prelude::*};
use log::{info, LevelFilter};
/**
* Specify <link data-trunk rel="copy-dir" href="src/assets" />
* in the index.html to copy the files!!
*
* You'll see them in the dist directory!
*/
fn main() {
dioxus_logger::init(LevelFilter::Info).expect("failed to init logger");
dioxus::web::launch(app);
}
fn app(cx: Scope) -> Element {
let mut index = use_state(&cx, || 1);
let change_evt = move |evt: KeyboardEvent| match evt.key.as_str() {
"ArrowRight" => index += 1,
"ArrowLeft" => index -= 1,
_ => {}
};
let url = format!("/assets/img/wallpaper/1042/0{}.jpg", index);
cx.render(rsx!(img {
src: "{url}",
onkeydown: change_evt,
}))
}
在 JavaScript 中会是这样的
document.addEventListener('keydown', (evt) => {
// Do magic
}
我尝试遵循calculator example但无法让它工作。
有什么想法吗?
最佳答案
这就是我最终在 Yew 所做的事情。
我使用了 wasm_bindgen 和 web_sys。这可能对 Dioxus 有用
use wasm_bindgen::{prelude::Closure, JsCast, UnwrapThrowExt};
use web_sys::window;
use_effect(move || {
let callback = Closure::wrap(Box::new(move |e: web_sys::KeyboardEvent| {
let key = e.key();
let key_str = key.as_str();
match key_str {
"ArrowLeft" => {
// Do something here
}
"ArrowRight" => {
// Do something here
}
_ => {}
}
}) as Box<dyn FnMut(_)>);
win.add_event_listener_with_callback("keydown", callback.as_ref().unchecked_ref())
.unwrap();
move || {
win.remove_event_listener_with_callback("keydown", callback.as_ref().unchecked_ref())
.unwrap();
}
});
这是cargo.toml的一部分
[dependencies]
web-sys = { version = "0.3.60", features = ['console'] }
wasm-bindgen = { version = "0.2.83" }
关于rust - 如何在 Dioxus 中添加全局 keydown 事件监听器)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74833748/